Ashik’s IT Thoughts

January 30, 2008

Rounding problem in Java for float, double types

Filed under: Uncategorized — Tags: , , , , — ashikuzzaman @ 3:28 pm

Here is a sample java program that I wrote. It shows that for all of Double, double, Float, float you can’t rely on default rounding operation of java/jvm. I think even JVM to JVM implementation (sun windows jvm vs ibm linux jvm for example) the output may vary. Can someone confirm it?

public class DoubleAndFloatIssue {

public static void main(String[] args) {

Float f1 = new Float(7.0004443556783244696789123456789f);
float f2 = 7.0004443556783244696789123456789f;

Double d1 = new Double(7.0004443556783244696789123456789);
double d2 = 7.0004443556783244696789123456789;

System.out.println(“Float f1 = ” + f1);
System.out.println(“float f2 = ” + f2);

System.out.println(“Double d1 = ” + d1);
System.out.println(“double d2 = ” + d2);

f1 = f1/7;
f2 = f2/7;

d1 = d1/7;
d2 = d2/7;

System.out.println(“Float f1/7 = ” + f1);
System.out.println(“float f2/7 = ” + f2);

System.out.println(“Double d1/7 = ” + d1);
System.out.println(“double d2/7 = ” + d2);

f1 = f1*7;
f2 = f2*7;

d1 = d1*7;
d2 = d2*7;

System.out.println(“Float (f1/7)*7 = ” + f1);
System.out.println(“float (f2/7)*7 = ” + f2);

System.out.println(“Double (d1/7)*7 = ” + d1);
System.out.println(“double (d2/7)*7 = ” + d2);

}

}

The output of the program is as below:

Float f1 = 7.0004444
float f2 = 7.0004444
Double d1 = 7.000444355678325
double d2 = 7.000444355678325
Float f1/7 = 1.0000635
float f2/7 = 1.0000635
Double d1/7 = 1.0000634793826177
double d2/7 = 1.0000634793826177
Float (f1/7)*7 = 7.000445
float (f2/7)*7 = 7.000445
Double (d1/7)*7 = 7.000444355678324
double (d2/7)*7 = 7.000444355678324

Create a free website or blog at WordPress.com.