Funny issue with casting double to ulong
Basile B via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jul 2 20:57:25 PDT 2017
On Monday, 3 July 2017 at 03:50:14 UTC, Saurabh Das wrote:
> Consider this snippet:
>
> void main()
> {
> import std.stdio;
> auto a = 6.2151;
> auto b = a * 10000;
> auto c = cast(ulong)b;
> writeln("a: ", typeof(a).stringof, " ", a);
> writeln("b: ", typeof(b).stringof, " ", b);
> writeln("c: ", typeof(c).stringof, " ", c);
>
> auto x = 62151.0;
> auto y = cast(ulong)x;
> writeln("x: ", typeof(x).stringof, " ", x);
> writeln("y: ", typeof(y).stringof, " ", y);
> }
>
> The output is:
> a: double 6.2151
> b: double 62151
> c: ulong 62150
> x: double 62151
> y: ulong 62151
>
> Why does c round off from 62151 to 62150 when casting to ulong?
>
> Thanks,
> Saurabh
6.251 has no perfect double representation. It's real value is:
6.21509999999999962483343551867E0
Hence when you cast to ulong after the product by 10_000, this is
the equivalent of
trunc(62150.9999999999962483343551867E0)
which gives 62150
CQFD ;-]
More information about the Digitalmars-d-learn
mailing list