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?

- 5,272
- 2
- 29
- 50
-
3Use `BigDecimal` class. – brso05 Jun 04 '15 at 18:55
-
2for why this doesn't come out exactly, see [Why not use Double or Float to represent currency?](http://stackoverflow.com/q/3730019/217324) – Nathan Hughes Jun 04 '15 at 19:48
2 Answers
That's the result of using floating point arithmetic, you have two options:
Math.round
the result of that operation, but i guess this is not what you want.- Use
java.math.BigDecimal
(arbitrary precision decimals) that allows you to store those decimal without loss of precision.

- 19,081
- 8
- 48
- 55
-
1Works well enough:) Apparently, I can't accept yet, so that's coming soon (expect it in about 1 hour!) – hyper-neutrino Jun 04 '15 at 19:00
-
-
It's not fixed point arithmetic - it's using `double`, which is floating point. – Jon Skeet Jun 04 '15 at 19:02
-
-
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, BigDecimal
s 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.

- 949
- 1
- 10
- 19