Floating point arithmetic is not always precise.
In particular there is no exact representation of 10.2 as a floating point value, so the nearest representable value is stored instead. This value will be very slightly different from 10.2.
The simplest way to handle it is to round the numbers to a certain number of decimal places when you display them.
Some languages have a decimal
type that can represent 10.2 exactly. However:
- Javascript has no built in type like this, so you'd have to use a third-party library.
- Decimal floating point numbers don't solve all problems. For example the result of
0.1 / 0.3
cannot be represented exactly as a decimal. You may still need to round results to a certain number of decimal places when you display them.