This week's book giveaway is in the Big Data forum. We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line! See this thread for details.

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?

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 ]

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 ]