4

In Java, I've noticed that 1.1+(2.2*(3.3+4.4)) results in 18.040000000000003, rather than 18.04. Is there a way to prevent this from happening?

hyper-neutrino
  • 5,272
  • 2
  • 29
  • 50

2 Answers2

3

That's the result of using floating point arithmetic, you have two options:

  1. Math.round the result of that operation, but i guess this is not what you want.
  2. Use java.math.BigDecimal (arbitrary precision decimals) that allows you to store those decimal without loss of precision.
uraimo
  • 19,081
  • 8
  • 48
  • 55
1

If your goal requires precise calculation with full control over the precision, then I would suggest using BigDecimal class. BigDecimal allows one to set very precise rules with which the calculations are done by setting the number of digits after the division point, rounding mode and by accepting a MathContext as an argument.

There are however some drawbacks. First off, BigDecimals are objects thus all operations are done via methods, and not using standard math operators. This is a bit cumbersome, especially while building more complex expressions, and if not done carefully might lead to some nasty, unclead code. Secondly, since as was said, all operations are done on objects, they are more heavy resource-wise.

ttarczynski
  • 949
  • 1
  • 10
  • 19