java-BigDecimal 使用

1、因为计算机使用浮点运算  有时候使用double时候 计算出来的不是你需要的数据,精度准确,也别是财务计算时不大方便,

此时需要使用BigDecimal类来进行计算。

package cn.burce.API3;

import java.math.BigDecimal;
import java.math.BigInteger;

public class SystemLearn {
    public static void main(String[] args) {
        test();
    }

    public static void test() {
        BigInteger b1 = new BigInteger("11111111111111111111");// 要是字符串
        BigInteger b2 = new BigInteger("99999999999999999999");
        BigInteger b3 = b1.add(b2);// 加法
        System.out.println(b3);
        System.out.println(b2.subtract(b1));// 减法
        System.out.println(b1.multiply(b2));// 乘法
        System.out.println(0.09 + 0.01);//可以看到结果不是0.01,而是0.0099999999999
        BigDecimal decimal = new BigDecimal("0.09");
        BigDecimal decimal1 = new BigDecimal("0.01");
        System.out.println(decimal.add(decimal1));// 加法

    }
}

猜你喜欢

转载自www.cnblogs.com/BruceKing/p/13364540.html