前言
Java中当一个数的超过long型范围(能够表示64位的整数)时可以使用BigInteger和BigDecimal类型:
一、BigInteger
推荐使用BigInteger(String val)构造方法,还可以对其进行加减乘除四则运算,分别是add、subtract、multiply和divide:
public class Main {
public static void main(String[] args) {
BigInteger bigInteger1=new BigInteger("333333333333");
BigInteger bigInteger2=new BigInteger("444444444444");
System.out.println("两个数分别是"+bigInteger1+"和"+bigInteger2);
//BigInteger类型数字的四则运算
//加
System.out.println(bigInteger1.add(bigInteger2));
//减
System.out.println(bigInteger1.subtract(bigInteger2));
//乘
System.out.println(bigInteger1.multiply(bigInteger2));
//除
System.out.println(bigInteger1.divide(bigInteger2));
}
}
BigInteger相关API如下:
二、BigDecimal
根据运行结果发现,实际的的运算结果跟我们想要的结果是不同的,而是一个无限接近我们理想的值,原因是由于:在计算机中使用的是二进制,而浮点数运算会导致不精确。
使用BigDecimal类可以用于计算超级大型的浮点数,并且能够提供高精度的浮点运算。
注意:如果除法运算能够整除,那么BigDecimal的除法运算和BigInteger的divide方法是一样的,
但是如果不能整除的话会出现报错
,因此需要使用其它的divide重载方法。
BigDecimal相关API如下: