Casting double to ulong weirdness

via Digitalmars-d digitalmars-d at puremagic.com
Tue Aug 25 06:51:17 PDT 2015


On Tuesday, 25 August 2015 at 11:14:35 UTC, Steven Schveighoffer 
wrote:
> On 8/24/15 5:34 PM, "=?UTF-8?B?Ik3DoXJjaW8=?= Martins\" 
> <marcioapm at gmail.com>\"" wrote:
>> On Monday, 24 August 2015 at 21:03:50 UTC, Steven 
>> Schveighoffer wrote:
>
>>> I understand the inconsistency, and I agree it is an issue 
>>> that should
>>> be examined. But the issue is entirely avoidable by not using
>>> incorrect methods to convert from floating point to integer 
>>> after
>>> floating point operations introduce some small level of error.
>>>
>>> Perhaps there is some way to make it properly round in this 
>>> case, but
>>> I guarantee it will not fix all floating point errors.
>>>
>>
>> What is the correct way to truncate, not round, a 
>> floating-point value
>> to an integer?
>
> auto result = cast(ulong)(x * 10.0 + x.epsilon);
>
> -Steve

import std.stdio;
void main() {
	double x = 1.2;
	writeln(cast(ulong)(x * 10.0 + x.epsilon));

	double y = x * 10.0;
	writeln(cast(ulong)(y + x.epsilon));
	
	double z = x * 10.0 + x.epsilon;
	writeln(cast(ulong)(z));
}

Outputs:
11
12
12

I leave it at this. It seems like this only bothers me, and I 
have no more time to argue.
The workaround is not that bad, and at the end of the day, it is 
just one more thing on the list.


More information about the Digitalmars-d mailing list