# Why (int)(0.29 * 100) = 28 in Java?

Printable View

• 08-14-2011, 06:32 AM
rootnet47
Why (int)(0.29 * 100) = 28 in Java?
(int)(0.29 * 100) = 28
Could anybody explain me that why Java results unexpected in such case? But in case of
(int)(0.29f * 100) = 29. whether 0.29 itself is a double in default. :(-:
• 08-14-2011, 06:42 AM
Fubarable
This is not a Java error, but a general problem of programming languages trying to represent floating point numbers using digital hardware -- no language can represent the numbers with perfect precision as it just can't be done. So you must take care when doing floating point calculations to take this into consideration. One solution is to format the out put so that it makes sense. So:

Code:

import java.text.DecimalFormat;

public class Foo002 {
public static void main(String[] args) {
double d = 0.29 * 100;
System.out.println("as a double: " + d);
System.out.println("don't cast the double as an int: " + (int)d);

DecimalFormat decFormat = new DecimalFormat("0");
System.out.println("instead, format the number: " + decFormat.format(d));

decFormat.applyPattern("0.00000");
System.out.println("and a more accurate format: " + decFormat.format(d));
}
}

• 08-15-2011, 05:29 AM
stchman
Try this, this seems to correct the problem.

String.format( "%.0f", 0.29 * 100 );
• 08-15-2011, 02:31 PM
KevinWorkman
Quote:

Originally Posted by stchman
Try this, this seems to correct the problem.

String.format( "%.0f", 0.29 * 100 );

That only "corrects the problem" in the same way that casting it to a float does. Fubarable already asked the question, but for more information, google "what every computer scientist should know about floating point arithmetic".
• 08-15-2011, 02:42 PM
JeffGrigg
Binary floating point representations, like float and double cannot represent values like 0.1 and 0.01 exactly; the value stored will always be a little more or a little less than what you might think or intend. So truncating rather than rounding can cause undesirable results.

Code:

double doubleValue = 0.29 * 100;
System.out.println("doubleValue = " + String.format("%.15f", doubleValue));
int truncatedValue = (int) doubleValue;
System.out.println("truncatedValue = " + truncatedValue);
long roundedValue = Math.round(doubleValue);
System.out.println("roundedValue = " + roundedValue);

Output:
Code:

doubleValue = 28.999999999999996
truncatedValue = 28
roundedValue = 29