首页 / 操作系统 / Linux / 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多线程操作遍历问题 http://www.linuxidc.com/Linux/2013-01/78574.htmJava多线程顺序执行 http://www.linuxidc.com/Linux/2012-07/65033.htmJava多线程问题之同步器CyclicBarrier http://www.linuxidc.com/Linux/2012-07/64593.htmJava多线程之wait()和notify() http://www.linuxidc.com/Linux/2012-03/57067.htmJava多线程之synchronized http://www.linuxidc.com/Linux/2012-03/57068.htmJava多线程之并发锁 http://www.linuxidc.com/Linux/2012-03/57069.htmJava多线程之ThreadPool http://www.linuxidc.com/Linux/2012-03/57071.htmJava多线程之ThreadLocal http://www.linuxidc.com/Linux/2012-03/57070.htm