Alternative Floating Point Arithmetic

In most cases these issues can be ignored or tolerated, but for correct results you should use a precise type such as BigDecimal. In this blog post I want to discuss an alternative approach.

As an example for this alternative approach, I will take the typical use case of some type of price. Since most currencies go up to two decimal digits, you would have to store this as a floating point (or double). Due to the known exact precision (which in this case is two decimal points), my proposed approach would be to store this in an integer (or long) with the value in cents. This means that an amount of 2.99 would be stored as 299.

What are the effects of this approach? First of all, compared to a float you will actually increase the range of supported values and you will be able to represent all values correctly without any rounding. Calculations will need to be done using floating point arithmetic and be converted back to an integer value where some rounding may be needed.

As an example we can take the value of 299 (2.99) and take 21% of it. This calculation in floating point would be 2.99 x 0.21 = 0.6279. It is however completely overkill to have this precision as it is impossible to go lower than two digits as it is just impossible to anything less then 1 cent. So in this case rounding would dictate it to become 0.63

Doing the same calculation with our integer value: 299 x 0.21 = 62.79 yields the same result. As said earlier, we do have to do this calculation with floating point arithmetic after which it can be converted to the correct integer (63 in this case).

Storing an integer requires less space than a BigDecimal and should allow for faster calculations. I am however in no way suggesting that you should never use BigDecimal anymore. The BigDecimal has many other features and does allow for more certainty than just an integer or long. When going for this approach you should have confidence over the values you are dealing with and make sure that all surrounding logic is safe and sound.