Java's digital precision computing problem-bigdecimal

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.