Java 中大数的处理方案BigInteger和BigDecimal类的使用

BigInteger和BigDecimal的介绍

应用场景:
1、BigInteger适合保存比较大的整型
2、BigDecimal适合保存精度更高的浮点型(小数)

一、BigInteger类的使用详解,代码如下

public class BigInteger_ {
    
    
    public static void main(String[] args) {
    
    
        //当我们编程中,需要处理很大的整数,long不够用
        //可以使用BigInteger的类来搞定
//        long l = 234459897895499999999999999999999l;
//        System.out.println("l=" + l);

        BigInteger bigInteger = new BigInteger("234459897895499999999999999999999");
        System.out.println(bigInteger);
        //1.在对BigInteger进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /
        BigInteger bigInteger2 = new BigInteger("100");
        BigInteger add = bigInteger.add(bigInteger2);
        System.out.println(add);//+

        BigInteger subtract = bigInteger.subtract(bigInteger2);
        System.out.println(subtract); //减

        BigInteger divide = bigInteger.divide(bigInteger2);
        System.out.println(divide);//除

    }
}

输出结果如下

234459897895499999999999999999999
234459897895500000000000000000099
234459897895499999999999999999899
2344598978954999999999999999999

二、BigDecimal类的使用详解,代码如下

public class BigDecimal_ {
    
    
    public static void main(String[] args) {
    
    
        //当我们需要保存一个精度很高的数时,double不够用
        //可以用BigDecimal
//        double d=19999.2323223423493423423432423;
//        System.out.println(d);

        BigDecimal bigDecimal = new BigDecimal("19999.2323223423493423423432423");
        BigDecimal bigDecimal2 = new BigDecimal("1.1");
        System.out.println(bigDecimal);

        //1.如果对BigDecimal进行运算,比如加减乘除,需要使用对应的方法
        //2.创建一个需要操作的BigDecimal然后调用相应的方法即可
        System.out.println(bigDecimal.add(bigDecimal2));//+
        System.out.println(bigDecimal.subtract(bigDecimal2));//-
        System.out.println(bigDecimal.multiply(bigDecimal2));//*
        //在调用divide 方法时,指定精度即可.BigDecimal.ROUND_CEILING
        //如果有无限循环小数,就会保留分子的精度 就是定义的bigDecimal 数对应的分子的精度,小数点后的位数
        //不指定精度,可能就会抛出异常
        System.out.println(bigDecimal.divide(bigDecimal2, BigDecimal.ROUND_CEILING));// /  可能抛出异常ArithmeticException
    }
}

输出结果如下

19999.2323223423493423423432423
20000.3323223423493423423432423
19998.1323223423493423423432423
21999.15555457658427657657756653
18181.1202930384994021294029476

猜你喜欢

转载自blog.csdn.net/lu202032/article/details/124492324