大数就是没有精度要求和没有舍入误差的数值类型。
java.math 包中的 BigInteger 和 BigDecimal 两个类可以处理包含任意长度数字序列的数值。
- BigInteger 类实现了任意精度的整数运算。
- BigDecimal 实现了任意精度的浮点数运算。
使用大数的情形:
- 无法接受舍入误差计算中。
例如金融计算,命令
System.out.pritnln(2.0 - 1.1)
将打印出0.8999999999999999
,而不是人们期望的0.9
。 - 基本的整数和浮点数精度不能够满足需求。
使用静态的 valueOf 方法可以将普通的数值转换为大数:
BigInteger a = BigInteger.valueOf(100);
对于更大的数,可以使用一个带字符串参数的构造器:
BigInteger b = new BigInteger("123456789123456789123456789123456789123456789");
一些 BigInteger 常量:
- BigInteger.ZERO
- BigInteger.ONE
- BigInteger.TEN
- BigInteger.TWO (Java 9 之后增加的)
大数不能使用熟悉的算术运算符处理大数,而需要使用大数类的方法。
API java.math.BigInteger 1.1
- Biglnteger add(Biglnteger other)
返回这个大整数和另一个大整数 other 的和。
- Biglnteger subtract(Biglnteger other)
返回这个大整数和另一个大整数 other 的差。
- Biglnteger multipiy(Biginteger other)
返回这个大整数和另一个大整数 other 的积。
- Biglnteger divide(Biglnteger other)
返回这个大整数和另一个大整数 other 的商。
- Biglnteger mod(Biglnteger other)
返回这个大整数和另一个大整数 other 的余数。
- BigInteger sqrt() 9
得到这个 BigInteger 的平方根。
- int compareTo(Biglnteger other)
如果这个大整数与另一个大整数 other 相等,返回 0; 如果这个大整数小于另一个大整数 other, 返回负数; 否则,返回正数。
- static Biglnteger valueOf(1ong x)
返回值等于 x 的大整数。
API java.math.BigDecimal 1.1
- BigDecimal add(BigDecimal other)
返回这个大实数与另一个大实数 other 的和。
- BigDecimal subtract(BigDecimal other)
返回这个大实数与另一个大实数 other 的差。
- BigDecimal multipiy(BigDecimal other)
返回这个大实数与另一个大实数 other 的积。
- BigDecimal divide(BigDecimal other)
- BigDecimal divide(BigDecimal other, RoundingMode mode) 5
返回这个大实数与另一个大实数 other 的商。如果商是无限循环小数,第一个 divide 方法会抛出一个异常。要得到一个舍入的结果,就要使用第二个 divide 方法。RoundingMode.HALF_UP 是在学校中学习的四舍五入方式(即, 数值0到4舍去,数值5到9进位)。它适用于常规的计算。其他舍入方法可以参考 API 文档。
- int compareTo(BigDecimal other)
如果这个大实数与 other 相等,返回 0;如果这个大实数小于 other, 返回负数; 否则,返回正数。
- static BigDecimal valueOf(1ong x)
- static BigDecimal valueOf(1ong x, int scale)
返回值为 X 或 x / 10scale 的一个大实数。