When I assign 2.3211232f as value to a float variable in Java it is assigned as 2.3211231 to that variable. Why does this happen ?
-
Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/q/588004/5221149) – Andreas Nov 02 '19 at 16:25
-
Any particular reason to use float rather than double? – Patricia Shanahan Nov 05 '19 at 16:30
2 Answers
In Java, floating-point values are denominated in units of powers of two. For numbers between 2 and 4, the unit used for float
is 2−22. This is because float
has 24-bit significands, so, when the high bit represents 21, as it must for numbers between 2 and 4, the low bit represents 21−23 = 2−22.
2−22 is 0.0000002384185791015625, so the representable numbers between 2 and 4 are spaced in steps of that size. The representable numbers near 2.3211232 are:
- 2.3211228847503662109375
- 2.3211231231689453125000
- 2.3211233615875244140625
Of those, 2.3211231231689453125000 is the closest to 2.3211232, so, when the source text 2.3211232f
is converted to float
, the result is 2.3211231231689453125000.
Java’s default formatting displays this as “2.3211231”, because it uses just enough decimal digits to uniquely identify the value. It does not show all the digits of the exact value, so it misrepresents the value. Never take the result of default formatting as the actual value.

- 195,579
- 13
- 168
- 312
A Java float
is a 32-bit floating-point value. Wikipedia says:
This gives from 6 to 9 significant decimal digits precision.
Your number has 8 digits, and it seems that it exceeding what a float
can handle.
If you want to see the precision at the value you have, call the Math.ulp(float f)
method.
If you want to see what next value down/up a float
can handle, use the Math.nextDown(float f)
and Math.nextUp(float f)
methods.
float f = 2.3211232f;
System.out.println("f = " + f);
System.out.println("down = " + Math.nextDown(f));
System.out.println("up = " + Math.nextUp(f));
System.out.println("ulp = " + Math.ulp(f));
Output
f = 2.3211231
down = 2.321123
up = 2.3211234
ulp = 2.3841858E-7
As you can see, your value 2.3211232
cannot be stored in a float
, because the next value up from 2.3211231
is 2.3211234
.
As the ULP (Unit in the Last Place) shows, the precision at the last (7th) digit is 2.4, so there is between 2 and 3 steps in the 7th digit between adjacent values.

- 154,647
- 11
- 152
- 247