1

I want my math value to break when the value is 0.8. But the program just keep going and i don´t get the result that Im searching for.

double math = 5.0;

while (true) {
    if (math ==  0.8) {
        break;
    }
    math -= 0.2;
    System.out.println (math);
}
System.out.println ("Your math value is done.");
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
  • Take a look at this answer https://stackoverflow.com/questions/322749/retain-precision-with-double-in-java – Adam Rice Oct 21 '17 at 09:24

3 Answers3

1

You have a problem with floating point precision. If you run your code through the debugger probably the value which is calculated is not exactly 0.8, but something like e.g: 0.79999999999999785

You could try to define a threshold in your condition so that it breaks the loop. Here is an example how you can do it:

double math = 5.0;

double delta = 0.001;
while (true) {

    if (math > 0.8 - delta && math < 0.8 + delta)
        break;
    math -= 0.2;
    System.out.println(math);
}
System.out.println("Your math value is done.");

Rounding errors are a "feature" of floating point arithmetic in computers. See section on rounding errors in this article.

gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
1

Use BigDecimal for calculations if you want to maintain precision.

Also see: Java:Why should we use BigDecimal instead of Double in the real world?

sashwat
  • 607
  • 4
  • 10
0

Check delta between math and 0.8 to see if it's within a certain level of precision you've defined for your program before breaking out the loop.

if (Math.abs(math - 0.8) < 0.00000001) {
   break;
}
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81