首页 > 代码库 > Java BigDecimal类

Java BigDecimal类

 1 package demo04;
 2 
 3 import java.math.BigDecimal;
 4 
 5 //double和float类型在运算中很容易丢失精度,造成数据的不准确性,BigDecimal类可以实现浮点数据的高精度运算
 6 public class BigDecimalDemo {
 7     public static void main(String[] args) {
 8         BigDecimal b1 = new BigDecimal("0.09");
 9         BigDecimal b2 = new BigDecimal("0.01");
10         
11         //
12         BigDecimal add = b1.add(b2);
13         System.out.println(add);
14         
15         //
16         BigDecimal b3 = new BigDecimal("1");
17         BigDecimal b4 = new BigDecimal("0.32");
18         BigDecimal sub = b3.subtract(b4);
19         System.out.println(sub);
20         
21         //
22         BigDecimal b5 = new BigDecimal("1.015");
23         BigDecimal b6 = new BigDecimal("100");
24         BigDecimal mul = b5.multiply(b6);
25         System.out.println(mul);
26         
27         //除 BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) 
28         BigDecimal b7 = new BigDecimal("1.301");
29         BigDecimal b8 = new BigDecimal("101");
30         BigDecimal div = b7.divide(b8,2,BigDecimal.ROUND_UP);        //0.02
31         BigDecimal div1 = b7.divide(b8,2,BigDecimal.ROUND_DOWN);     //0.01
32         BigDecimal div2 = b7.divide(b8,2,BigDecimal.ROUND_HALF_UP);  //四舍五入
33         System.out.println(div);
34         System.out.println(div1);
35         System.out.println(div2);
36     }
37 }

 

Java BigDecimal类