Adding with double or float data types can be very strange

For example, println (4.63 + 0.6) outputs 5.22999999999995

Adding with double or float data types can be very strange

For example, println (4.63 + 0.6) outputs 5.22999999999995

This is caused by the way that floating point numbers are represented as bytes. If you want to know the details of how it works I suggest you look into IEEE 754 which is the standard that defines them.

The best analogy I personally have is this:

When you see a number like `0.3333333`

you probably think, yeah that is `1/3`

. We know it takes infinite many decimal places to write out that number. The same is true for binary encoding. Some floating point numbers are easy to represent and others would need an infinite number of digits, eg. `1/5`

. So when you try to represent a number that would need an infinite number of digits (or just more than `float`

or `double`

allows, the next closets number is used instead. This small error can add up over time so if you need very exact calculations (eg. for monetary transactions, banking, etc) you should use a class like `BigDecimal`

instead. This allows to represent all floating point numbers exactly (with the cost of slower calculation time and a larger memory footprint).

2 Likes

I don’t understand. Isn’t 4.63 + 0.6 equal to 5.23?

The following articles may be useful:

What Every Programmer Should Know About Floating-Point Arithmetic

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Thanks