Precision Issue


public static void main(String[] args) {

System.out.println("=============================================");
System.out.println("Result for double (primitive type)");
double val = 0;
for (int i = 0; i <>
val += 0.1d;
System.out.println(val);
}
System.out.println("=============================================");
System.out.println("Result for Double (Class type)");
Double d = 0D;
for (int i = 0; i <>
d += new Double("0.1");
System.out.println(d);
}
System.out.println("=============================================");
System.out.println("Result for BigDecimal initialized with String");
BigDecimal bd = new BigDecimal(0);
for (int i = 0; i <>
bd = bd.add(new BigDecimal("0.1"));
System.out.println(bd);
}
System.out.println("=============================================");
System.out.println("Result for BigDecimal initialized with double");
BigDecimal abd = new BigDecimal(0);
for (int i = 0; i <>
abd = abd.add(new BigDecimal(0.1D));
System.out.println(abd);
}
System.out.println("=============================================");
}


Executing the codes above will give you the result of:
=============================================
Result for double (primitive type)
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
=============================================
Result for Double (Class type)
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
=============================================
Result for BigDecimal initialized with String
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
=============================================
Result for BigDecimal initialized with double
0.1000000000000000055511151231257827021181583404541015625
0.2000000000000000111022302462515654042363166809082031250
0.3000000000000000166533453693773481063544750213623046875
0.4000000000000000222044604925031308084726333618164062500
0.5000000000000000277555756156289135105907917022705078125
0.6000000000000000333066907387546962127089500427246093750
0.7000000000000000388578058618804789148271083831787109375
0.8000000000000000444089209850062616169452667236328125000
0.9000000000000000499600361081320443190634250640869140625
1.0000000000000000555111512312578270211815834045410156250
=============================================



Conclusion:
  • Define the digits and decimal places constraint for every number in the application.
  • Use BigDecimal initialized with String for every computation which need exact precision.
  • Store the database in Number Format (defined with how much digits and decimal).
  • Be careful in dealing with precision issue especially for an application which needs balance calculation.

0 comments: (+add yours?)