Java's digital operations, occasionally drinking the problem of the occurrence of precision, the following illustrates the use of the Java BigDecimal class.
For example:
System.out.println (0.9+0.3); Results 1.2
System.out.println (1.9+0.3); Results 2.1999999999999997
System.out.println (1.9+0.4); Results 2.3
Java provides the BigDecimal class for accurate calculation of the float or double type.
Examples are as follows:
public static BigDecimal Getbigdecimal (Double val) {
Replace the double with BigDecimal
return new BigDecimal (Val);
}
public static BigDecimal getbigdecimal (int val) {
Replace int with BigDecimal
return new BigDecimal (Val);
}
public static BigDecimal Getbigdecimal (String val) {
Replace the string with BigDecimal
return new BigDecimal (Val);
}
On the line addition operation
public static double Add (double d1,double D2) {
BigDecimal B1=getbigdecimal (D1);
BigDecimal B2=getbigdecimal (D2);
Return B1.add (B2). Doublevalue ();
}
Rounding operations
public static double round (double D,int len) {
BigDecimal B1=getbigdecimal (d);
BigDecimal B2=getbigdecimal (1);
Return B1.divide (B2,LEN,BIGDECIMAL.ROUND_HALF_UP). Doublevalue ();
}
Last attempt output:
System.out.println (1.9+0.3); Result is 2.1999999999999997
System.out.println (Round (Add (1.9,0.3), 2)); Result is 2.2
It is so sour, the above from the network.
Java's digital precision computing problem-bigdecimal