BigInteger與BigDecimal
BigInteger類
Integer類作為int的包裝類,能儲存的最大整型值為2 31-1,Long類也是有限的, 最大為2 63-1。如果要表示再大的整數,不管是基本資料型別還是他們的包裝類 都無能為力,更不用說進行運算了。
java.math包的BigInteger可以表示不可變的任意精度的整數。BigInteger 提供 所有 Java 的基本整數操作符的對應物,並提供 java.lang.Math 的所有相關方法。 另外,BigInteger 還提供以下運算:模算術、GCD 計算、質數測試、素數生成、 位操作以及一些其他操作。
構造器
- BigInteger(String val):根據字串構建BigInteger物件
常用方法
- public BigInteger abs():返回此 BigInteger 的絕對值的 BigInteger。
- BigInteger add(BigInteger val) :返回其值為 (this + val) 的 BigInteger
- BigInteger subtract(BigInteger val) :返回其值為 (this - val) 的 BigInteger
- BigInteger multiply(BigInteger val) :返回其值為 (this * val) 的 BigInteger
- BigInteger divide(BigInteger val) :返回其值為 (this / val) 的 BigInteger。整數 相除只保留整數部分。
- BigInteger remainder(BigInteger val) :返回其值為 (this % val) 的 BigInteger。
- BigInteger[] divideAndRemainder(BigInteger val):返回包含 (this / val) 後跟 (this % val) 的兩個 BigInteger 的陣列。
- BigInteger pow(int exponent) :返回其值為 (thisexponent) 的 BigInteger。
BigDecimal類
一般的Float類和Double類可以用來做科學計算或工程計算,但在商業計算中, 要求數字精度比較高,故用到java.math.BigDecimal類。
BigDecimal類支援不可變的、任意精度的有符號十進位制定點數。
構造器
- public BigDecimal(double val)
- public BigDecimal(String val)
常用方法
- public BigDecimal add(BigDecimal augend) //加
- public BigDecimal subtract(BigDecimal subtrahend) //減
- public BigDecimal multiply(BigDecimal multiplicand) //乘
- public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) //除
public void testBigInteger() {
BigInteger bi = new BigInteger("12433241123");
BigDecimal bd = new BigDecimal("12435.351");
BigDecimal bd2 = new BigDecimal("11");
System.out.println(bi);
// System.out.println(bd.divide(bd2));
System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));
System.out.println(bd.divide(bd2, 15, BigDecimal.ROUND_HALF_UP));
}
輸出結果
12433241123
1130.486
1130.486454545454545