0

I write the following code with a for loop.

double d1 = 0;
for (int i = 1; i <= 8; i++) {
    d1 += 0.1;
 }

System.out.println(d1);

The output is 0.7999999999999999. It is supposed to be 0.8. but I don't understand what causes it and how to avoid the rounding problem in the future.

Elias
  • 179
  • 8
  • 1
    *how to avoid the rounding problem in the future* use a type with arbitrary precision like [`BigDecimal`](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html) – Elliott Frisch Mar 26 '23 at 19:03
  • or accept that it exists and format your output to show an acceptable appearing result: `System.out.printf("%.4f%n", d1);` – Hovercraft Full Of Eels Mar 26 '23 at 21:11

0 Answers0