如果基本的证书和浮点数精度不能满足需求,这个时候可以使用java.math包中的BigInteger和BigDecimal。BigInteger实现了任意精度的整数运算,BigDecimal实现了任意精度的浮点数运算。
使用静态的valueOf方法可以将普通数值转换为大数值:
BigInteger a=BigInteger.valueOf(100);
不过无法使用算数运算符(如+和*)处理大数值。而需要使用大数值类中的add和multiply方法。示例代码如下:
import java.math.BigDecimal;
import java.math.BigInteger;
public class BigIntegerTest {
public static void main(String[] args) {
BigInteger a = BigInteger.valueOf(100);
BigInteger b = BigInteger.valueOf(30);
BigInteger c = a.add(b);
System.out.println(c);
BigInteger d = a.multiply(c);
System.out.println(d);
BigDecimal x = BigDecimal.valueOf(0.001);
BigDecimal y = BigDecimal.valueOf(1.223);
System.out.println(x.multiply(y));
}
}