如果基本的整数和浮点数精度不能够满足需求,可以用java.math包中的两个重要的类:BigInteger和BigDecimal;BigInteger实现了任意精度的整数运算,BigDecimal实现了任意精度的浮点数运算。
加、减、乘、除运算demo
@Test
public void BigDateTest(){
BigInteger bigInt = new BigInteger("9999999");
BigInteger bigInt_2 = new BigInteger("111111");
System.out.println("相加值:" + bigInt.add(bigInt_2));
System.out.println("相减值:" + bigInt.subtract(bigInt_2));
System.out.println("乘积值:" + bigInt.multiply(bigInt_2));
System.out.println("相除值:" + bigInt.divide(bigInt_2));
System.out.println("*************");
BigDecimal dec = new BigDecimal("99.99");
BigDecimal dec2 = new BigDecimal("10");
System.out.println("相加值:" + dec.add(dec2));
System.out.println("相减值:" + dec.subtract(dec2));
System.out.println("乘积值:" + dec.multiply(dec2));
System.out.println("相除值:" + dec.divide(dec2));
}
}
运行结果:
相加值:10111110
相减值:9888888
乘积值:1111109888889
相除值:90
*************
相加值:109.99
相减值:89.99
乘积值:999.90
相除值:9.999