Bookmark Topic Watch Topic
  • New Topic

Java Subtraction Error?  RSS feed

 
Mike DeStefano
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Report post to moderator
Riddle me this - Why is it when the executed code below produces the unexpected results also below?

Code -
double dblTest = 1.00;
while (dblTest > 0) {
System.out.println("dblTest = " + dblTest);
dblTest -= .05;
}

Results -
dblTest = 1.0
dblTest = 0.95
dblTest = 0.8999999999999999
dblTest = 0.8499999999999999
dblTest = 0.7999999999999998
dblTest = 0.7499999999999998
dblTest = 0.6999999999999997
dblTest = 0.6499999999999997
dblTest = 0.5999999999999996
dblTest = 0.5499999999999996
dblTest = 0.4999999999999996
dblTest = 0.4499999999999996
dblTest = 0.39999999999999963
dblTest = 0.34999999999999964
dblTest = 0.29999999999999966
dblTest = 0.24999999999999967
dblTest = 0.19999999999999968
dblTest = 0.1499999999999997
dblTest = 0.09999999999999969
dblTest = 0.049999999999999684

How do I fix this?

Thanks in advance,
- Mike
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Report post to moderator
Please do not cross post the same question in multiple forums. Please direct all answers here
 
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!