Java中的BigInteger类和BigDecimal类

本文介绍了Java中的BigInteger和BigDecimal类,前者用于处理大整数,后者处理高精度浮点数。它们在进行加减乘除操作时需使用相应方法,特别提到BigDecimal除法时可能遇到的精度问题及解决方案。
摘要由CSDN通过智能技术生成

BigInteger类和BigDecimal类

BigInteger适合保存比较大的整型

  1. 当我们编程中,需要处理很大的整数,long不够用,可以使用BigInteger的了来搞定
  2. 在对BigInteger进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /,可以创建一个要操作的BigInteger然后进行相应的操作
    BigInteger.add()
    BigInteger.subtract()
    BigInteger.multiply()
    BigInteger.divide()
   public class BigInteger_ {
        public static void main(String[] args) {
            BigInteger bigInteger = new BigInteger("-9999999999999999");
            BigInteger bigInteger1 = new BigInteger("-2");
            System.out.println(bigInteger);
            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);
        }
}

在这里插入图片描述

BigDecimal适合保存精度更高的浮点型

  1. 当我们需要保存一个很高精度的数时,double不够用可以用BigDecimal
  2. 在对BigDecimal进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /,可以创建一个要操作的BigDecimal然后进行相应的操作
    注意在除法运算时可能除不整,会出异常
    在这里插入图片描述

解决方法:
在调用divide方法时,指定精度即可,BigDecimal.ROUND_CEILING
如果有无线循环小数,就会保留分子的精度,修改如下。

BigDecimal divide = bigDecimal.divide(bigDecimal1,BigDecimal.ROUND_CEILING);

调用方法和用法和BigInteger一样,同上

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值