-4

When I add two numbers together I get Calculation error like that:

0.1 + 0.2 = 0.30000000000000004

Can I solve this problem without rounding the result?

2 Answers2

1

In short: No. Try googeling floating point arithmetic. That should answer all your questions.

https://0.30000000000000004.com/

"Floating point is broken" duplicates

https://floating-point-gui.de/

  • This is almost a link-only answer, the only saving grace is the "no". In the future it's best to at least summarize the information in the link. https://meta.stackoverflow.com/a/288056/238704 – President James K. Polk Nov 29 '21 at 20:57
  • It isn't. The link is merely an extra-hint. The main-part of this answer is the "keyword" floating point arithmetic. If you look that up in any search engine you'll instantly get an answer. –  Nov 29 '21 at 21:19
0

You also could use something different from Double, like BigDecimal:

BigDecimal.valueOf(0.1) + BigDecimal.valueOf(0.2)
Javier Montón
  • 4,601
  • 3
  • 21
  • 29