I've been experimenting with Java floats, and I've noticed some weird behaviour that doesn't appear to occur in another language, like C#.
// Expecting 'x' to round down to 1500.455.
float x = 1500.45504f;
// Expecting 'y' to round up to 2000.3741.
float y = 2000.37408f;
System.out.println(x + ", " + y);
The above code produces the output 1101.4551, 1106.374
. Should the rounding not be consistent for both floats? Why is the 1101.45504 round to .4551
, whereas the 1106.37408 value is being essentially truncated to .374
? Should it not be the other way around?
Edit: The main intention behind this question was asking why different languages treat floats differently. As Eric has mentioned, Java's Float.ToString()
method does append one more digit to distinguish between adjacent floats, but why is this not the case for C#? And how can I represent this behaviour in other languages, such as C#.