Floating point rounding error

Udesh Kavinda
2 min readOct 1, 2021

So you’ve written some absurdly simple code, say for example:

0.1 + 0.2

and got a really unexpected result:

0.30000000000000004

This can be considered as a bug in Java, but it is not. This has little to do with Java, and much more to do with how the underlying platform handles floating-point numbers. It’s a normal case encountered when handling floating-point numbers internally in a system. It’s a problem caused when the IEEE 754 representation of floating-point numbers, which uses a fixed number of binary digits to represent a decimal number. It is difficult to represent some decimal number in binary, so in many cases, it leads to small roundoff errors.

If this is wrong why oracle team don’t fix this issue ?

Actually it has nothing to do with Java. It happens because it is the way the underlying c platform handles floating-point numbers and ultimately with the inaccuracy, They don’t fix this issue because this is the way it’s meant to be. because floating point number calculation is more faster and more efficient in this way (In this case efficient mean the memory allocated to the floating number is more small in this way). We can always use Bigdecimal to avoid this error.

--

--

Udesh Kavinda
Udesh Kavinda

No responses yet