Double value is rounded to unexpected value: 2.5 -> 2 instead of 3
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jul 7 11:59:47 PDT 2017
On 07/07/2017 11:29 AM, alex_ca wrote:
> input 2.5 10 10
> stitches: 2.5 -> 2
> I expect: 3
That's because what is printed as 2.5 is actually a little less than
that. (Try printing with a format string like "%.20f".)
The common way of dealing with this issue is to add 0.5 before the
conversion:
import std.stdio;
import std.conv;
void main() {
for (double d = 1; d < 2; d += 0.1) {
writefln("%s (%.20f): %s", d, d, (d + 0.5).to!int);
}
}
1 (1.00000000000000000000): 1
1.1 (1.10000000000000008882): 1
1.2 (1.20000000000000017764): 1
1.3 (1.30000000000000026645): 1
1.4 (1.40000000000000035527): 1
1.5 (1.50000000000000044409): 2
1.6 (1.60000000000000053291): 2
1.7 (1.70000000000000062172): 2
1.8 (1.80000000000000071054): 2
1.9 (1.90000000000000079936): 2
Ali
More information about the Digitalmars-d-learn
mailing list