Java知识点——大数值(BigInteger BigDecimal)

当基本数据类型的精度不足时,Java提供java.math包的BigInteger和BigDecimal类进行大数值运算。BigInteger支持任意精度的整数操作,而BigDecimal则处理任意精度的浮点数。这两个类不支持常规的算术运算符,而是通过add、multiply等方法进行数学运算。本文将介绍这两个类的常用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果基本的整数和浮点数精度不能够满足需求, 那么可以使用java.math 包中的两个很有用的类:BiglntegerBigDecimal。 这两个类可以处理包含任意长度数字序列的数值。Biglnteger 类实现了任意精度的整数运算,BigDecimal 实现了任意精度的浮点数运算。使用静态的 valueOf方法可以将普通的数值转换为大数值:

	Biglnteger a = Biglnteger.valueOf(100);

遗憾的是,不能使用人们熟悉的算术运算符(如:+ 和 *) 处理大数值。 而需要使用大数值类中的 add 和 multiply 方法

	Biglnteger c = a.add(b); // c = a + b
	Biglnteger d = c.multiply(b.add(Biglnteger.val ueOf(2))); // d = c * (b + 2)

下面的 API 注释汇总了Biglnteger 最常用的方法

方法实现功能
Biglnteger add(Biglnteger other)返冋这个大整数和另一个大整数 other的和
Biglnteger subtract(Biglnteger other)返冋这个大整数和另一个大整数 other的差
Biglnteger multiply(Biginteger other)返冋这个大整数和另一个大整数 other的积
Biglnteger divide(Biglnteger other)返冋这个大整数和另一个大整数 other的商
Biglnteger mod(Biglnteger other)返冋这个大整数和另一个大整数 other的余数
int compareTo(Biglnteger other)如果这个大整数与另一个大整数 other 相等, 返回 0; 如果这个大整数小于另一个大整数 other, 返回负数; 否则, 返回正数。
static Biglnteger valueOf(long x)返回值等于 x 的大整数。

下面的 API 注释汇总了BigDecimal 最常用的方法

方法实现功能
BigDecimal add(BigDecimal other)返回这个大实数与另一个大实数 other 的和
BigDecimal subtract(BigDecimal other)返回这个大实数与另一个大实数 other 的差
BigDecimal multiply(BigDecimal other)返回这个大实数与另一个大实数 other 的积
BigDecimal divide(BigDecimal other,RoundingMode mode)返回这个大实数与另一个大实数 other 的商。要想计算商,必须给出舍入方式。RoundingMode.HALF UP 是四舍五入方式。
int compareTo(BigDecimal other)如果这个大实数与另一个大实数相等, 返回 0 ; 如果这个大实数小于另一个大实数,返回负数;否则,返回正数。
static BigDecimal valueOf(long x)返回值为x的一个大实数。
static BigDecimal valueOf(long x ,int scale)返回值为 x / 10^scale 的一个大实数。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值