Convert double to long if lossless
drug
drug2004 at bk.ru
Tue Jan 19 16:14:17 UTC 2021
On 1/19/21 6:50 PM, Ali Çehreli wrote:
> On 1/19/21 6:04 AM, drug wrote:
>
> > Another (low level) way is to shift mantissa left by exponent value.
>
> Luckily, we already have a helper in Phobos:
>
> https://dlang.org/phobos/std_bitmanip.html#FloatRep
>
> Ali
>
That makes life simpler, thanks for sharing this:
```D
import std;
void main()
{
auto valueRange = [
10.000000000000001,
10.0000000000000001, // in fact this is just 10.0
];
foreach(value; valueRange)
{
auto dr = DoubleRep(value);
const hasFractional = !!(dr.fraction << (dr.exponent-1023+12));
writefln("has `%.18f` fractional part: %s", value, hasFractional);
}
}
```
but I think that casting to long and comparing it to the value is easier
to understand and more portable:
```D
import std;
void main()
{
auto valueRange = [
10.000000000000001,
10.0000000000000001, // in fact this is 10.0
];
foreach(value; valueRange)
{
const hasFractional = (value != cast(long)value);
writefln("has `%.18f` fractional part: %s", value, hasFractional);
}
}
```
P.S. shouldn't compiler emit the error if a literal can't be represented
lossless?
More information about the Digitalmars-d-learn
mailing list