BigInteger类和BigDecimal类

本文介绍了Java中用于处理大整数的BigInteger类和高精度浮点数的BigDecimal类。BigInteger提供加减乘除操作,避免了溢出问题。BigDecimal则适用于需要精确计算的小数,通过指定精度处理除不尽的情况。示例代码展示了如何使用这两个类进行数学运算。
摘要由CSDN通过智能技术生成

BigInteger类和BigDecimal类

BigInteger类基本介绍

  • BigInteger 适合保存比较大的整型

  • 在对 BigInteger 类的变量进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /

public class test {
    public static void main(String[] args) {
        BigInteger bigInteger = new BigInteger("234999999999999999999999999999");
        BigInteger bigInteger1 = new BigInteger("100");

        BigInteger add = bigInteger.add(bigInteger1); //加
        BigInteger subtract = bigInteger.subtract(bigInteger1);//减
        BigInteger multiply = bigInteger.multiply(bigInteger1);//乘
        BigInteger divide = bigInteger.divide(bigInteger1);//除

        System.out.println(add);
        System.out.println(subtract);
        System.out.println(multiply);
        System.out.println(divide);
    }
}

 

BigDecimal类基本介绍

  • BigDecimal 适合保存精度更高的浮点型(小数)

  • 在对 BigDecimal类的变量进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /

  • 在调用 divide() 方法时,可能会抛出异常 ArithmeticException (算术结果为无限循环小数,即除不尽),只需要在调用divide() 方法时,指定精度即可。

  • 指定精度BigDecimal.ROUND_CEILING ,如果有无限循环小数,就会保留分子的精度

public class test {
    public static void main(String[] args) {
        BigDecimal bigDecimal = new BigDecimal("1223.111111111199999999999999998");
        BigDecimal bigDecimal2 = new BigDecimal("3");
        
        BigDecimal add = bigDecimal.add(bigDecimal2);
        BigDecimal subtract = bigDecimal.subtract(bigDecimal2);
        BigDecimal multiply = bigDecimal.multiply(bigDecimal2);
        BigDecimal divide = bigDecimal.divide(bigDecimal2,BigDecimal.ROUND_CEILING);
        
        System.out.println(add);
        System.out.println(subtract);
        System.out.println(multiply);
        System.out.println(divide);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值