On 1/19/21 6:42 AM, Per Nordlöw wrote:
I want to convert a double to a long if conversion is lossless (without fractional part, non-nan, non-inf, within long-range, etc).

I currently have

void foo()
{
     const double value = 10.1;
     try
     {
         import std.conv : to;
         const lvalue = value.to!long;
         if (lvalue == value)
         {
             writeln("lvalue:", lvalue);
             return;
         }
     }
     catch (Exception e) {}
     writeln("value:", value);
}

Can this be improved?

For instance how do I check if a float/double/real has a fractional part and avoid entering try-catch for those cases?

Use a cast instead.

const lvalue = cast(long)value;

-Steve

Reply via email to