cast(int) getting an unexpected number

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Wed Nov 4 23:13:19 PST 2009


Joel Christensen 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.


If the values you are working with are monetary, I don't think it makes 
sense to convert to int by casting, since casting always rounds towards 
zero. Instead you should use the std.math.lround() function, which 
rounds in a more natural way (towards the nearest integer, away from 
zero if the fractional part is exactly 0.5).

To answer your question, this is how you would get and use the epsilon 
value in your example:

   cast(int)(f*100f + float.epsilon);

-Lars


More information about the Digitalmars-d-learn mailing list