File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes double subtraction Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "double subtraction" Watch "double subtraction" New topic

double subtraction

Tony Stoyle

Joined: May 16, 2002
Posts: 11
Does anyone know what on earth is going on here? This code is inside a JSP page but I guess that is academic -
double f1 = 569.56;
double f2 = 316.505;
double f3 = f1 - f2;
The result should be 253.055 but is coming out as 253.05499999999995 .............
Any advice appreciated before I go mad! Thanks.
Wilfried LAURENT
Ranch Hand

Joined: Jul 13, 2001
Posts: 269
There have been several threads on the same topics. See for example:

thread 1
thread 2
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
This past conversations in the Cattle Drive mentions links that describe well what is going on.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Blame the IEEE.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

try using java.math.BigDecimal using a String as a constructor. For some reason it keeps the correct precision.

The result is 253.055
Not exactly what I call efficient though!
Tony Stoyle

Joined: May 16, 2002
Posts: 11
Many thanks for your replies..
I agree. Here's the link:
subject: double subtraction
It's not a secret anymore!