std.conv.to vs. casting

Ali Çehreli acehreli at yahoo.com
Thu Jul 4 09:16:07 PDT 2013


On 07/04/2013 03:15 AM, Joseph Rushton Wakeling wrote:

 > The cast should be safe, as it's a size_t to a double.

I am commenting without fully understanding the context: Both size_t and 
double are 64 bit types on a 64-bit system. double.mant_dig being 53, 
converting from size_t to double loses information for many values.

import std.stdio;
import std.conv;

void main()
{
     size_t i = 0x8000_0000_0000_0001;
     double d0 = i.to!double;
     double d1 = cast(double)i;

     writefln("%s", i);
     writefln("%f", d0);
     writefln("%f", d1);
}

Prints

9223372036854775809
9223372036854775808.000000
9223372036854775808.000000

Still, the same information loss in a comparison may make one think that 
it actually worked! :p

     assert(d0 == i);    // passes!
     assert(d1 == i);    // passes!

Ali



More information about the Digitalmars-d-learn mailing list