I have a code that works using loop but it's bad imo, because can be simplified. I mean this loop:
private static long GetFract(double d)
{
if (d < 0)
return GetFract(-d);
d -= Math.Truncate(d);
long result = 0;
checked
{
while (true)
{
try
{
d *= 10;
long tmp = (long)d;
if (Math.Abs(tmp - d) < double.Epsilon)
return tmp;
result = tmp;
}
catch
{
return result;
}
}
}
}
expected results: 2.3333
-> 3333
so can we use IEEE754
to get a fractional part of a number without using ToString()
, Split()
and other functions, using just FP and integer math? I mean some bit magic:
private static unsafe long GetFract(double d)
{
if (d < 0)
return GetFract(-d);
d -= Math.Truncate(d);
const long mask = 0xFFFFFFFFFFFFF; //some magic const here
long x = *((long*) &d);
return x & mask;
}
we assume that d is always in [0..1], long and double are 8 bytes both