JAVA常用類之——BigInteger和BigDecimal
1. 先來看BigInteger,它用來進行超過Integer範圍的數據的操作,進行如下測試:
public static void main(String[] args)
{
//1. 獲得Integer的最大值
// 可以看到Integer的範圍是-2^32 - 2^32-1
System.out.println(Integer.MAX_VALUE);
Integer i = new Integer(2147483647);
//Integer不能解決超過最大值的運算操作,編譯都不會通過
//Integer ii = new Integer(2147483648);
//2. 下面這種方法說明Integer的最大值是2147483647
// 再加+1後該數溢出變爲-2147483648
Integer ii = new Integer(2147483647+1);
System.out.println(ii);
//3. 採用BigInteger可以獲得超過Integer範圍的數的操作
BigInteger iii = new BigInteger("21474836488888");
System.out.println(iii);
}
對BigInteger進行加減乘除操作如下所示:
public static void main(String[] args)
{
//1. 創建兩個大數對像
BigInteger bi1 = new BigInteger("2147483648");
BigInteger bi2 = new BigInteger("214748364888888888888888");
//2. 測試加法
System.out.println(bi1.add(bi2));
//3. 測試減法
System.out.println(bi1.subtract(bi2));
//4. 測試乘法
System.out.println(bi1.multiply(bi2));
//5. 測試除法
System.out.println(bi2.divide(bi1));
//6. 測試valueof方法
System.out.println(BigInteger.valueOf(21474836488888888L));
}
2. 再來看看BigDecimal
BigDecimal是解決float和double的精度丟失而出現的。