Convert double to long if lossless
Steven Schveighoffer
schveiguy at gmail.com
Tue Jan 19 13:36:58 UTC 2021
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
More information about the Digitalmars-d-learn
mailing list