java BigInteger类和BigDecimal

文章介绍了Java中的BigInteger类用于处理大整数的加减乘除操作,以及BigDecimal类在确保浮点数运算精度方面的应用。示例代码展示了如何进行基本的数学运算,并强调了这两个类在处理精度要求高的计算时的重要性。
摘要由CSDN通过智能技术生成

java BigInteger类

BigInteger功能

可以对大整数进行运算

BigInteger加减乘除

构造方法:
        public BigInter(String value)
        //可以将整数的字符串,转化为BigInteger对象

 成员方法:
        public BigInter add(BigInter value)   超大整数加法运算
        public BigInter subtract(BigInter value)   超大整数减法运算
        public BigInter multiply(BigInter value)   超大整数乘法运算
        public BigInter divide(BigInter value)   超大整数除法运算

使用方法

public class BigIntegerDemo {
    public static void main(String[] args) {
        BigInteger bigInteger = new BigInteger("200");
        BigInteger result1 = bigInteger.add(new BigInteger("100"));
        System.out.println(result1);
        //200 = 200 + 100;

        BigInteger result2 = bigInteger.subtract(new BigInteger("50"));
        System.out.println(result2);
        //150 = 200 - 50;

        BigInteger result3 = bigInteger.multiply(new BigInteger("2"));
        System.out.println(result3);
        //400 = 200 * 2;

        BigInteger result4 = bigInteger.divide(new BigInteger("2"));
        System.out.println(result4);
        //100 = 200 / 2;

    }
}

java BigDecimal类

使用场景

BigDecimal可以对大浮点数进行运算,保证运算的精确性。float,double
他们在存储运算的时候,会导致数据精度的丢失。如果要保证运算的准确性,
就需要使用BigDecimal.

BigDecimal加减乘除

 构造方法:
        public BigDecimal(String val) 将BigDecimal的字符串表示形式转化为 BigDecimal

 成员方法:
        public BigDecimal add(BigDecimal value)    加法运算
        public BigDecimal subtract(BigDecimal value)    减法运算
        public BigDecimal multiply(BigDecimal value)    乘法运算
        public BigDecimal divide(BigDecimal value)    除法运算(除不尽会有异常)
        public BigDecimal divide(BigDecimal divisor , int scale ,int roundingMode) 除法运算(除不使用该方法)

        参数说明:
            scale 精确位数
            roundingMode 取舍模式
                BigDecimal.ROUND_HALF_UP 四舍五入
                BigDecimal.ROUND_FLOOR  去尾法
                BigDecimal.ROUND_UP   进一法

使用方法

public class BigDecimalDemo {
    public static void main(String[] args) {
        BigDecimal bigDecimal1 = new BigDecimal("10");
        BigDecimal bigDecimal2 = new BigDecimal("3");

        BigDecimal add = bigDecimal1.add(bigDecimal2);
        System.out.println(add);
        //13

        BigDecimal subtract = bigDecimal1.subtract(bigDecimal2);
        System.out.println(subtract);
        //7

        BigDecimal multiply = bigDecimal1.multiply(bigDecimal2);
        System.out.println(multiply);
        //30

        BigDecimal divide = bigDecimal1.divide(bigDecimal2, 3, BigDecimal.ROUND_FLOOR);
        System.out.println(divide);
        //3.333


    }
}

学的不是技术,更是梦想!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

君生我老

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

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

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

打赏作者

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

抵扣说明:

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

余额充值