Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Problem when subtracting 2 floating point numbers

807588Feb 26 2009 — edited Feb 27 2009
When I try to subtract 0.1 from 4.1 I get the result 3.999999....

I understand the cause of the problem from reading this article: http://mindprod.com/jgloss/floatingpoint.html

I also notice that the following code gives the correct answer:
double a = 4.1;
double b = 0.1;

double c = a*10;
double d = b*10;
double e = c-d;
double f = e/10;

System.out.println(f);
However it is very important that the code I am producing never has this rounding precision error. Can someone tell me if the above code will always avoid the floating point problem? Does anyone have any better alternative suggestions on how to tackle this problem?

Thankyou in advance,
Chris
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 27 2009
Added on Feb 26 2009
15 comments
582 views