digitalmars.D.learn - Best way to convert and apply floor()
- Daniele M. (15/15) Apr 06 2014 Hello guys/girls,
- anonymous (17/25) Apr 06 2014 I'd advise you to avoid casts, especially when you're starting
- monarch_dodra (8/11) Apr 06 2014 Well, conversion to int "drops" the fractional part, rounding
Hello guys/girls, I have read almost completely the book and I am very much interested in D language. However sometimes I have doubts that I cannot clearly cut out, thus I thought it would be a good idea to ask the community. 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)); // x == 3 Thanks in advance! -- Daniele
Apr 06 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 == 3I'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
Apr 06 2014
On Sunday, 6 April 2014 at 09:23:21 UTC, anonymous wrote: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.Well, conversion to int "drops" the fractional part, rounding *towards* 0, whereas floor floor will reduce to the lower integral. It can make a difference for negatives: auto x = -3.5; floor(x); // => -4 cast(int)x; // => -3
Apr 06 2014