To solve the accuracy problem: BigDecimal

BigDecimal class

  BigDecimal package where : Classes in java.math, immutable, arbitrary-precision signed decimal numbers. BigDecimal an arbitrary precision integer unscaled value and a 32-bit integer scale (Scale) composition.

  For calculation precision without any precise figure can be used as float or double, if desired result of accurate calculation, you must use the BigDecimal class, and using the BigDecimal class can also operate large numbers of

dobule examples

 1 public class TestMath {
 2 
 3     public static void main(String[] args) {
 4         double a1 = 0.1;
 5         double a2 = 0.2;
 6         
 7         double a3 = a1 + a2;
 8         System.out.println(a1 + " + " + a2 + " = " + a3);
 9     }
10 
11 }

Guess the result is how much?

Results: 0.1 + 0.2 = 0.30000000000000004

(Common sense should be 0.1 + 0.2 = 0.3)

BigDecimal examples

 1 import java.math.BigDecimal;
 2 
 3 public class TestMath {
 4 
 5     public static void main(String[] args) {
 6         double a1 = 0.1;
 7         double a2 = 0.2;
 8         
 9         double a3 = a1 + a2;
10         System.out.println("使用double类型计算结果:" + a1 + " + " + a2 + " = " + a3);
11         
12         BigDecimal b1 = new BigDecimal("0.1");
13         BigDecimal b2 = newBigDecimal ( "0.2" );
 14          
15          BigDecimal B3 = b1.add (B2);
 16          
. 17          System.out.println ( "Type BigDecimal using the calculation result:" + B1 + "+" + B2 + "=" + B3) ;
 18      }
 . 19  
20 is }

Output:

The results using double type: 0.1 + 0.2 = 0.30000000000000004
use BigDecimal type calculation: 0.1 + 0.2 = 0.3

Guess you like

Origin www.cnblogs.com/zhuitian/p/11486871.html