java 常用类库:BigInteger大整数;BigDecimal大小数(解决double精度损失);

2021-06-05 09:05

阅读:561

标签:ima   zha   技术   ack   png   alt   ber   author   zhang   

大整数BigInteger

package com.zmd.common_class_libraries;

import java.math.BigInteger;

/**
 * @ClassName BigNumberExample
 * @projectName: object1
 * @author: Zhangmingda
 * @description: XXX
 * date: 2021/4/7.
 */
public class BigNumberExample {
    public static void main(String[] args) {
        BigInteger a = new BigInteger("999999999999999999999999999999999999999999");
        BigInteger b = new BigInteger("888888888888888888888888888888888888888888");
        //加法
        System.out.println(a.add(b));
        //减法
        System.out.println(a.subtract(b));
        //乘法
        System.out.println(a.multiply(b));
        //除法
        System.out.println(a.divide(b));
    }
}

 

技术图片

 

长小数BigDecimal

package com.zmd.common_class_libraries;

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

        BigDecimal a = new BigDecimal("999999999999999999999999999999999999999999.999999999999999999999999999999999999999999");
        BigDecimal b = new BigDecimal("888888888888888888888888888888888888888888.888888888888888888888888888888888888888888");
        //加法
        System.out.println(a.add(b));
        //减法
        System.out.println(a.subtract(b));
        //乘法
        System.out.println(a.multiply(b));
        //除法
        System.out.println(a.divide(b));
    }
}

技术图片

 

 double 精度损失

package com.zmd.common_class_libraries;

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

/**
 * @ClassName BigNumberExample
 * @projectName: object1
 * @author: Zhangmingda
 * @description: XXX
 * date: 2021/4/7.
 */
public class BigNumberExample {
    public static void main(String[] args) {
        //double精度损失
        double da = 0.05;
        double db = 0.01;
        System.out.println(da + db);
        //等于0.060000000000000005

        //BigDecimal可以解决此问题
        BigDecimal ba = new BigDecimal("0.05");
        BigDecimal bb = new BigDecimal("0.01");
        System.out.println(ba.add(bb));
        //0.06
    }
}

 

java 常用类库:BigInteger大整数;BigDecimal大小数(解决double精度损失);

标签:ima   zha   技术   ack   png   alt   ber   author   zhang   

原文地址:https://www.cnblogs.com/zhangmingda/p/14627741.html


评论


亲,登录后才可以留言!