Java中的大数值
在Java中,如果基本的整数Integer和浮点数Double的精度不能满足需求,那么可以使用java.math
包中的两个类:BigInteger
和BigDecimal
。这两个类可以处理包含任意长度数字序列的数值。BigInteger
类实现了任意精度的整数运算,BigDecimal
实现了任意精度的浮点数运算。
BigInteger
// 对于BigInteger不能使用算术运算符直接处理,而需要使用以下方法
BigInteger add(BigInteger other)// 和
BigInteger subtract(BigInteger other)// 差
BigInteger multiply(BigInteger other)// 积
BigInteger divide(BigInteger other)// 商
BigInteger mod(BigInteger other)// 余数
// 如果这个大整数与另一个大整数other相等,返回0;如果小于,返回负数;否则返回正数
int compareTo(BigInteger other)
// 返回值等于x的大整数
static BigInteger valueOf(long x)
BigDecimal
// 同样,BigDecimal也不能直接使用运算符运算
BigDecimal add(BigDecimal other)// 和
BigDecimal subtract(BigDecimal other)// 差
BigDecimal multiply(BigDecimal other)// 积
// 商,在计算商时,必须给出舍入方式(rounding mode),RoundingMode是枚举类型,常用的是RoundingMode.HALF_UP(四舍五入)
BigDecimal divide(BigDecimal other, RoundingMode mode)
// 如果这个大实数与另一个大实数other相等,返回0;如果小于,返回负数;否则返回正数
int compareTo(BigDecimal other)
// 返回值为x的大实数
static BigDecimal valueOf(long x)
static BigDecimal valueOf(double x)
// 返回值为x/(10^scale)的大实数
static BigDecimal valueOf(long x, int scale)