cast(int) getting an unexpected number

Steven Schveighoffer schveiguy at yahoo.com
Thu Nov 5 10:41:58 PST 2009


On Wed, 04 Nov 2009 19:38:45 -0500, Joel Christensen <joelcnz at gmail.com>  
wrote:

>> To be safe, whenever converting to int, always add a small epsilon.  I  
>> think you can use float.epsilon, but I don't have any experience with  
>> whether that is always reasonable.
>>  -Steve
>
> Thanks every one for the replies.
>
> I still have problems. How do I use epsilon? 'real' helps in my example  
> program but not in my money program. I think there's a function out  
> there that does dollars and cents (eg. .89 -> 89c and 1.00 -> $1), but  
> I'm interested how to solve this problem.

Might I suggest using integers instead of floating point.

My experience with floating point is limited, but I've been burned enough  
to avoid using it wherever possible.  To be fair, there are certainly many  
cases where floating point is useful, like in statistics, but when I can  
use integers, I do.

Translating money into integers is as easy as using the lowest  
denomination as 1.

For example, if you always store your money in cents, then $1 is simply  
stored as 100.  If you want to add tax (say 5%), you do x * 5 / 100.  If  
you want to do rounding, then it's a little trickier, but not too bad: (x  
* 5 + 50) / 100.  The trick is to add half the value of the denominator  
before dividing to do exact rounding.  I've written lots of code that uses  
decimal numbers without ever using floating point.

It's also fun to experiment with fraction types, which are more exact when  
you are dealing with rational numbers.  I once had a very comprehensive  
C++ fraction type that used a templated base type for the  
numerator/denominator.  I even ported it to Java using BigInt as the  
numerator/denominator types.  It could do very exact calculations with  
pretty useable speed.  This was only in algorithmic coding competitions,  
I've never had a real world use for them (though I know they exist).

There are types in other languages such as C#'s decimal that do a lot of  
the work for you.  It would be a nice addition to D.

Hope this helps.

-Steve


More information about the Digitalmars-d-learn mailing list