您的位置:首页 > 编程语言 > Java开发

JAVA中的大数字BigInteger和BigDecimal

2013-09-24 20:30 316 查看
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)

本文出自 “意大利小乳猪” 博客,请务必保留此出处http://lovesisi.blog.51cto.com/6414433/1301207
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: