trying to convert some values around long.max from double to long yields negative values instead of something sensible (an overflow exception, or a large value in the order of magnitude of long.max).
import std;
void main()
{
writeln(9223372036854775296.0.to!long); // output -9223372036854775808 - bad
writeln(9223372036854776832.0.to!long); // output -9223372036854775808 - bad
writeln(9223372036854775295.0.to!long); // output 9223372036854774784 - ok
try {
writeln(9223372036854776833.0.to!long);
} catch (ConvOverflowException) {
writeln("exception"); // ok
}
}
Comment #1 by nick — 2022-12-05T12:35:10Z
to!long(double) calls toImpl which just does cast(long). The problem seems to be that casting a value bigger than 9223372036854775295 to long gives a negative result:
long l = 9223372036854775296;
assert(l < long.max);
double d = cast(double)l;
assert(cast(long)d > 0); // fails
However C with gcc does the same:
double d = 9223372036854775296L;
assert((long)d > 0); // fails
Comment #2 by robert.schadek — 2024-12-01T16:40:50Z