Java中的大数字BigInteger和BigDecimal

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)

相关阅读:

Java Hashtable多线程操作遍历问题

Java多线程顺序执行

Java多线程问题之同步器CyclicBarrier

Java多线程之wait()和notify()

Java多线程之synchronized

Java多线程之并发锁

Java多线程之ThreadPool

Java多线程之ThreadLocal

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/23246efaced0cf9d9d3bc969dced7ec0.html