【Java学习笔记】BigInteger 和 BigDecimal 类

BigInteger 和 BigDecimal 类

二者共有的常见方法

方法功能
add
subtract
multiply
divide

注意点:传参类型必须是类对象


一、BigInteger

1. 作用:适合保存比较大的整型数

2. 使用说明

  • 创建BigInteger对象

  • 传入字符串

3. 代码示例

import java.math.BigInteger;

public class main {
    public static void main(String[] args) {
        BigInteger bigInteger = new BigInteger("999999999999999999999999");
        System.out.println(bigInteger);

        BigInteger bigInteger1= new BigInteger("9");

        // 加法
        System.out.println("add:" + bigInteger.add(bigInteger1));

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

        // 乘法
        System.out.println("multiply:" + bigInteger.multiply(bigInteger1));

        // 除法
        System.out.println("divide:" + bigInteger.divide(bigInteger1));
    }
}

// 输出结果
999999999999999999999999
add:1000000000000000000000008
subtract:999999999999999999999990
multiply:8999999999999999999999991
divide:111111111111111111111111


二、BigDecimal

1. 作用:适合保存高精度浮点数(小数)

2. 使用说明

  • 创建BigInteger对象

  • 传入字符串

3. 注意点

BigDecimal使用除法的时候,会出现除不尽(无限循环小数)的情况,这个时候会抛出异常(ArithmeticException

解决方法

传参时候传入BigDecimal.ROUND_CEILING),这个时候结果的精度就会和分子保持一致

代码示例

import java.math.BigDecimal;

public class main {
    public static void main(String[] args) {
        BigDecimal bigDecimal = new BigDecimal("99.8888888888889999999");
        System.out.println(bigDecimal);

        BigDecimal bigDecimal1= new BigDecimal("7");

        // 加法
        System.out.println("add:" + bigDecimal.add(bigDecimal1));

        // 减法
        System.out.println("subtract:" + bigDecimal.subtract(bigDecimal1));

        // 乘法
        System.out.println("multiply:" + bigDecimal.multiply(bigDecimal1));

        // 除法
        System.out.println("divide:" + bigDecimal.divide(bigDecimal1,BigDecimal.ROUND_CEILING));
    }
}

// 输出结果
99.8888888888889999999
add:106.8888888888889999999
subtract:92.8888888888889999999
multiply:699.2222222222229999993
divide:14.2698412698412857143
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jackson凌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值