Best way to convert and apply floor()

anonymous anonymous at example.com
Sun Apr 6 02:23:21 PDT 2014


On Sunday, 6 April 2014 at 08:23:16 UTC, Daniele M. wrote:

> For example, is this the best way to perform a conversion + 
> floor?
>
> Input 'x' is a floating point expression that is never big 
> enough to justify usage of double or real type, but I picked 
> "real" because I noticed that it was the implicit cast type.
>
> auto s = "3.14";
> int x = cast(int)floor(to!real(x));

(assuming you meant to!real(s) here)

> // x == 3

I'd advise you to avoid casts, especially when you're starting
out with D. They're unsafe and you can easily blow your leg off
with them. std.conv.to does safe conversions. So, use to!int
instead of cast(int).

Conversion to int drops the fractional part, so you don't really
need floor. But if you think it makes the intent clearer, feel
free to leave it in.

With UFCS[1], dropped empty parentheses, and 'auto' for implicit
typing:

auto x = s.to!real.to!int;

You could try to avoid the double conversion and parse directly 
to int. But that would be a lot more work and error-prone, if you 
want to support all the formats that to!real recognizes. I think 
two conversions are fine.

[1] http://dlang.org/function.html#pseudo-member


More information about the Digitalmars-d-learn mailing list