一、大数
如果基本的整数和浮点精度不能够满足需求,那么可以使用Java.math包中两个很有用的类:BigInteger和BigDecimal。这两个类可以处理包含任意长度数字序列的数值。BigInteger类实现任意精度的整数运算,BigDecimal实现任意精度的浮点数运算。
使用静态的valueOf方法可以将普通的数值转换为大数:
BigInteger a = BigInteger.valueOf(100);
对于更大的数可以使用一个带字符串参数的构造器:
BigInteger reallyBig = new BigInteger("6465448966545646846546546546465454654654987987564654646546546");
另外还有一些常量:BigInteger.ZERO 、BigInteger.ONE和BigInteger.TEN,Java9之后还增加了BigInteger.TWO。
大数运算不能使用人们熟悉的算术运算符(如:+和*)处理大数。而需要使用大数类中的add和multiply方法。
BigInteger c = a.add(b);//c = a+b;
BigInteger d = c.multiplay(b.add(BigInteger.valueOf(2)));//d = c*(b+2);
java.math.BigInteger API
BigInteger add(BigInteger other) | 相加 |
BigInteger subtract(BigInteger other) | 相减 |
BigInteger multiply(BigInteger other) | 相乘 |
BigInteger divide(BigInteger other) | 相除 |
BigInteger mod(BigInteger other) | 取余 |
BigInteger sqrt() java 9 | 平方 |
int compareTo(BigInteger other) | 如果这个大整数与另一个大整数other相等返回0,如果这个大整数小于另一个大整数other返回负数,否则返回正数 |
static BigInteger valueOf(long x) | 返回等于的大整数 |
java.math.BigDecimal API
BigDecimal add(BigDecimal other) | 相加 |
BigDecimal subtract(BigDecimal other) | 相减 |
BigDecimal multiply(BigDecimal other) | 相乘 |
BigDecimal divide(BigDecimal other) | 相除 |
BigDecimal divide(BigDecimal other,RoundingMode mode) | 如果商是个无限循环小数,第一个divide方法会抛出一个异常。要得到一个四舍五入的结果就需要使用本方法。参数RoundingMode代表四舍五入的方式 |
int compareTo(BigDecimal other) | 如果这个大实数与另一个大实数other相等返回0,如果这个大实数小于另一个大实数other返回负数,否则返回正数 |
static BigDecimal valueOf(long x) | 返回等于的大整数 |
static BigDecimal valueOf(long x,int scale) | 返回值等于x或x/n<sup>2</sup> |