Java学习之路(三十三)| BigInteger和BigDecimal类

各自努力,最高处见!加油!

BigInteger和BigDecimal类的介绍

应用场景:

  • BigInteger适合保存比较大的整型。
  • BigDecimal适合保存精度更高的浮点型。

BigInteger及相关运算

在对BigInteger进行加减乘除的时候,需要使用对应的方法,不能直接进行加减乘除

import java.math.BigInteger;

public class BigInteger_ {
    public static void main(String[] args) {
        String str="237788888888888888888888888888";
        String str2="100";
        BigInteger bigInteger = new BigInteger(str);
        System.out.println(bigInteger);

        BigInteger bigInteger1 = new BigInteger(str2);
        BigInteger sum=bigInteger.add(bigInteger1);//加法
        System.out.println("和:"+sum);

        BigInteger subtract_=bigInteger.subtract(bigInteger1);//减法
        System.out.println("差:"+subtract_);

        BigInteger multiply_=bigInteger.multiply(bigInteger1);//乘法
        System.out.println("积:"+subtract_);

        BigInteger divide_=bigInteger.divide(bigInteger1);//乘法
        System.out.println("商:"+divide_);
    }
}

在这里插入图片描述

BigDecimal及相关运算

需要保存一个精度很高的数时,double不够用。

import java.math.BigDecimal;

public class BigDecimal_ {
    public static void main(String[] args) {
        BigDecimal bigDecimal = new BigDecimal("568888.8888888888888888888888888");
        BigDecimal bigDecimal1 = new BigDecimal("100");

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

在这里插入图片描述注意:除法除不尽的时候会抛出异常。解决:在调用的时候指定精度即可。

        System.out.println(bigDecimal.divide(bigDecimal1));//除法除不尽的时候会抛出异常。解决:在调用的时候指定精度即可。
        System.out.println(bigDecimal.divide(bigDecimal1,BigDecimal.ROUND_CEILING));//保留分子的精度,本例中为bigDecimal的精度
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值