大数处理方案

  1. BigInteger 适合保存比较大的整数。

    public class BigInteger_ {
        public static void main(String[] args) {
            //当我们编程中,需要处理很大的整数,long不够用
            //可以使用BigInteger的类来搞定
    //        long l = 132343214234332432445345l;
    //        System.out.println();
            BigInteger bigInteger = new BigInteger("1323432142343324376576567576576572445345");
            System.out.println(bigInteger);
            //1. 在对 BigInteger 进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /
            //2. 可以创建一个要操作的 BigInteger 然后进行相应 的操作
            BigInteger bigInteger1 = new BigInteger("100");
            //加
            BigInteger add = bigInteger.add(bigInteger1);
            System.out.println(add);
            //减
            BigInteger subtract = bigInteger.subtract(bigInteger1);
            System.out.println(subtract);
            //乘
            BigInteger multiply = bigInteger.multiply(bigInteger1);
            System.out.println(multiply);
            //除
            BigInteger divide = bigInteger.divide(bigInteger1);
            System.out.println(divide);
        }
    }
    //运行结果:
    //1323432142343324376576567576576572445345
    //1323432142343324376576567576576572445445
    //1323432142343324376576567576576572445245
    //132343214234332437657656757657657244534500
    //13234321423433243765765675765765724453
    
  2. BigDecimal 适合保存精度更高的浮点数(小数)。

    public class BigDecimal_ {
        public static void main(String[] args) {
            //当我们需要保存一个精度很高的数时,double不够用
            //可以使用 BigDecimal
            double d = 1.432452341211111111111151111111d;
            System.out.println(d);
            BigDecimal bigDecimal = new BigDecimal("1.432452341211111111111151111111");
            System.out.println(bigDecimal);
            //1. 如果对 BigDecimal 进行运算,比如加减乘除,需要使用对应的方法
            //2. 创建一个需要操作的 BigDecimal 然后调用其方法即可
            BigDecimal bigDecimal1 = new BigDecimal("1.1");
            //加
            System.out.println(bigDecimal.add(bigDecimal1));
            //减
            System.out.println(bigDecimal.subtract(bigDecimal1));
            //乘
            System.out.println(bigDecimal.multiply(bigDecimal1));
            //除
    //        System.out.println(bigDecimal.divide(bigDecimal1));//可能抛出异常ArithmeticException,因为结果可能是无限循环小数
            //解决方法在调用 divide 方法时, 指定其精度即可
            //如果有无限循环小数,就会保留 分子 的精度(分子的精度是多少,就保留多少精度)
           System.out.println(bigDecimal.divide(bigDecimal1,BigDecimal.ROUND_CEILING));
        }
    }
    //运行结果:
    //1.4324523412111112
    //1.432452341211111111111151111111
    //2.532452341211111111111151111111
    //0.332452341211111111111151111111
    //1.5756975753322222222222662222221
    //1.302229401101010101010137373738
    
  • BigInteger 和 BigDecimal 常见方法
    1. add 加
    2. subtract 减
    3. multiply 乘
    4. divide 除
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。