BigInteger和BigDecimal类

BigInteger 和 BigDecimal 介绍

应用场景

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

BigInteger 和 BigDecimal 常见方法

  • 1,add 加
  • 2,subtract 减
  • 3,multiply 乘
  • 4,divide 除

BigInteger方法:

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

        //在对BigInteger 进行操作时,需要使用对应的方法,不能直接用运算符;
        //可以创建一个要操作的 BigInteger 然后进行相应的操作
        BigInteger bigInteger1 = new BigInteger("1111111111111111111111");
        //加  bigInteger1+bigInteger
        BigInteger add = bigInteger1.add(bigInteger);
        System.out.println(add);//237888888999999999999999999991+1111111111111111111111
        //减 bigInteger1-bigInteger
        BigInteger subtract = bigInteger1.subtract(bigInteger);
        System.out.println(subtract);
        //乘  bigInteger1*bigInteger
        BigInteger multiply = bigInteger1.multiply(bigInteger);
        System.out.println(multiply);
        //除  bigInteger1/bigInteger
        BigInteger divide = bigInteger1.divide(bigInteger);
        System.out.println(divide);

    }
}

结果
在这里插入图片描述

BigDecimal方法:

public class BigDecimal_ {
    public static void main(String[] args) {
        //当我们需要保存一个精度很高的数,double不够用时,可以使用BigDecimal
        double d = 1999.11111111111999999999999977788222222;
        //输出 1999.11111111112  只能保存小数点后11位小数
        System.out.println(d);
        BigDecimal bigDecimal = new BigDecimal("1999.11111111111999999999999977788222222");
        // 输出 1999.11111111111999999999999977788222222
        System.out.println(bigDecimal);

        //如果对 BigDecimal 进行运算,比如加减乘除,需要使用对应的方法,
        // 创建一个需要操作的 BigDecimal 然后调用相应的方法即可
        BigDecimal bigDecimal1 = new BigDecimal(3);
        //bigDecimal+bigDecimal1
        System.out.println(bigDecimal.add(bigDecimal1));
        //bigDecimal-bigDecimal1
        System.out.println(bigDecimal.subtract(bigDecimal1));
        System.out.println(bigDecimal.multiply(bigDecimal1));
        //System.out.println(bigDecimal.divide(bigDecimal1));//会抛出异常ArithmeticException,因为可能为无限循环小数
        //解决办法:
        //在调用divide方法时,指定精度即可 BigDecimal.ROUND_CEILING,这样出现无限循环小数时,就会保留分子精度
        System.out.println(bigDecimal.divide(bigDecimal1,bigDecimal.ROUND_CEILING));
    }
}

结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值