大数处理方案

127 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

BigInteger和BigDecimal类

●BigInteger和BigDecimal介绍

应用场景:

  1. BigInteger适合保存比较大的整型
  2. BigDecimal适合保存精度更高的浮点型(小数)

案例演示

package www.xz.bignum;

import java.math.BigInteger;

/**
 * @author 许正
 * @version 1.0
 */
public class BigInteger_ {
    public static void main(String[] args) {
        BigInteger bigInteger = new BigInteger("23788888899999999999999999999");
        BigInteger bigInteger2 = new BigInteger("100");
        System.out.println(bigInteger);
        //1.在对BigInteger 进行加减乘除的时候,需要使用对应的方法,不能直接进行+ - * /
        //2.可以创建一个要操作的BigInteger然后进行相应操作
        BigInteger add = bigInteger.add(bigInteger2);
        System.out.println(add);//加法
        BigInteger subtract = bigInteger.subtract(bigInteger2);
        System.out.println(subtract);//减法
        BigInteger multiply = bigInteger.multiply(bigInteger2);
        System.out.println(multiply);//乘法
        BigInteger divide = bigInteger.divide(bigInteger2);
        System.out.println(divide);

    }
}
package www.xz.bignum;

import java.math.BigDecimal;

/**
 * @author 许正
 * @version 1.0
 */
public class BigDecimal_ {
    public static void main(String[] args) {
        BigDecimal bigDecimal = new BigDecimal("1999.11111111111111111111111111111");
        BigDecimal bigDecimal2 = new BigDecimal("1.1");
        System.out.println(bigDecimal);
        System.out.println(bigDecimal.add(bigDecimal2));
        System.out.println(bigDecimal.subtract(bigDecimal2));
        System.out.println(bigDecimal.multiply(bigDecimal2));
        //可能抛出异常ArithmeticException
//        System.out.println(bigDecimal.divide(bigDecimal2));
        //在调用divide方法时,指定精度即可。BigDecimal.ROUND_CEILING
        //如果有无限循坏小数,就会保留 分子 的精度
        System.out.println(bigDecimal.divide(bigDecimal2, BigDecimal.ROUND_CEILING));

    }
}