歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中的大數字BigInteger和BigDecimal

Java中的大數字BigInteger和BigDecimal

日期:2017/3/1 9:52:51   编辑:Linux編程

BigInteger 和 BigDecimal 是在java.math包中已有的類,前者表示整數,後者表示浮點數。

為什麼用大數字?

1) BigInteger:支持任意精度的整數,可以精確地表示任意大小的整數值,同時在運算過程中不會丟失任何信息。
2) BigInteger:可以精確地表示任意精度的小數,同時在運算過程中不會丟失任何信息。

注意:不能直接用符號如+、-來使用大數字,例如:
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
int a = 231, b = 423, c = 1393;
BigInteger x, y, z, ans;
x = BigInteger.valueOf(a);
y = BigInteger.valueOf(b);
z = BigInteger.valueOf(c);
ans = x.add(y); //加運算
System.out.print(ans+" ");
ans = z.divide(y); //除運算
System.out.print(ans+" ");
ans = x.mod(z); //模運算
System.out.print(ans+" ");
if (ans.compareTo(x) == 0) System.out.println("1");
}
}

運算結果:654 3 231 1

主要有以下方法可以使用:
BigInteger add(BigInteger other)
BigInteger subtract(BigInteger other)
BigInteger multiply(BigInteger other)
BigInteger divide(BigInteger other)
BigInteger mod(BigInteger other)
int compareTo(BigInteger other)
static BigInteger valueOf(long x)

Copyright © Linux教程網 All Rights Reserved