Thursday, January 12, 2012

Basic fundas about using float or double

Think again if you are going to use float or double for amount/currency field.

Reason behind this is

Floats have a fixed number of total bits of precision, which must be shared among the integer and fractional parts. If you use more of those bits to store a larger integer portion (123456 vs. just 12), that leaves fewer for the fractional portion (.4 vs. .45678).

Also, you should be aware that since float and double are base-2 formats, rather than base-10, many values that can be represented with a small, finite number of digits in base-10 cannot be stored in a double or float. For instance, it is impossible to store exactly 1/10 (0.1) in a double or float, just as it's impossible to store 1/3 (0.333...) exactly in a finite number of digits in base-10.

Demonstration code:

    public static void main(String args[]) {  
        double d = 1997500.43;  
        String s = "1997500.43";  
        float f = (float) d;  
        System.out.println(f);//1997500.4  
  
        float f3 = Float.parseFloat(s);  
        System.out.println(f3);//1997500.4  
  
        float f4 = Double.valueOf(s).floatValue();  
        System.out.println(f4);//1997500.4  
  
        float f5 = new Double(s).floatValue();  
        System.out.println(f5);//1997500.4  
  
        float xFloat;  
        Double x = new Double("63.8644951");  
        xFloat = x.floatValue();  
        System.out.println(xFloat);// 63.864494  
  
        float xFloat2;  
        Double x2 = new Double("3333263.8644951");  
        xFloat2 = x2.floatValue();  
        System.out.println(xFloat2);// 3333263.8  
}  

Detailed information about floats and doubles is available at : http://www.coderanch.com/t/564234/java/java/Precision-loss-String-Float-double

No comments:

Post a Comment