如果基本的證書和浮點數精度不能滿足需求,這個時候可以使用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));
}
}