This week's book giveaway is in the Kotlin forum.We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# A problem with a substract

Rafael Gutierrez
Greenhorn
Posts: 3
Hello everybody
In my code I have the next operations:
double d1 = 4.74;
double d2 = 4;
System.out.println(d1-d2);
and the printed result is '0.7400000000000002'.
Somebody knows why?

Wayne L Johnson
Ranch Hand
Posts: 399
Every 'real' value in Java--float and double--is stored in a binary representation as defined by the IEEE 754 standard. As such, many numbers may be only an approximation, and so you'll see small rounding errors such as the one you pointed out.
Think of it this way. If you add the fractions 1/3 + 2/3 you expect to get 3/3, or 1. However if you look at these in terms of decimal arithmetic you could get 0.3333333333 + 0.6666666666 = 0.9999999999.
If you'd like to get more information [than you'll probably ever need] on this subject, check out Floating Point Arithmetic on Sun's web site.
Please note that this problem isn't specific to Java: you can find similar problems in almost any programming language that supports floating point arithmetic.
[ September 05, 2003: Message edited by: Wayne L Johnson ]

Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
Very few fractions can be properly represented in floating point. Even that double that you put 4.74 into doesn't have the actual value 4.74. The println for double is designed to not show the actual contents but to truncate it off. Look at this code:

This will print the actual way that 4.74 is stored in a double:
4.7400000000000002131628207280300557613372802734375
[ September 05, 2003: Message edited by: Thomas Paul ]

Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
By the way, this program will do the correct calculation but notice that you have to use Strings in the constructor to get it to work right.

[ September 06, 2003: Message edited by: Thomas Paul ]

 It is sorta covered in the JavaRanch Style Guide.