Java语言学习
大数值
在实际编程中经常遇到整数和浮点数精度不能满足需求的情况,比如要表示一个很大的数,或者表示一个精度非常高的数,可以使用java.math包中的BigInteger和BigDecimal两个类,这两个类可以处理任意长度的数字。
定义格式:
BigInteger a = BigInteger.valueOf(1234567890);
BigDecimal b = BigDecimal.valueOf(1.234567891111111);
初始化时valueOf只能传递不大于10位的整数以及总位数小于18位的浮点型。
public static void main(String[] args) {
BigInteger a = BigInteger.valueOf(1234567890);
BigDecimal b = BigDecimal.valueOf(10000.234567891111111);
BigDecimal c = BigDecimal.valueOf(10001111111.2345678911111111111);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
运行结果如下:
运算
大树值不能直接用 **+ - * /**符合进行运算,需要调用相应的方法进行计算。
类型 | 方法 | 作用 |
---|---|---|
Biglnteger | add(Biglnteger other) | 整数加 |
Biglnteger | subtract(Biglnteger other) | 整数减 |
Biglnteger | multipiy(Biginteger other) | 整数乘 |
Biglnteger | divide(Biglnteger other) | 整数除 |
Biglnteger | mod(Biglnteger other) | 取余数 |
Biglnteger | int compareTo(Biglnteger other) | 比较两个数是否相等,相等返回0,否则返回整数 |
Biglnteger | static Biglnteger valueOf(long x) | 返回值等于x的大整数 |
BigDecimal | add(BigDecimal other) | 浮点数加 |
BigDecimal | subtract(BigDecimal other) | 浮点数减 |
BigDecimal | multipiy(BigDecimal other) | 浮点数乘 |
BigDecimal | divide(BigDecimal other RoundingMode mode) | 除 |
BigDecimal | int compareTo(BigDecimal other) | 比较 |
BigDecimal | static BigDecimal valueOf(1ong x) | |
BigDecimal | static BigDecimal valueOf(1ong x,int scale) | 返回值为 X 或 x / 10scale 的一个大实数 |
代码示例:
public static void main(String[] args) {
BigInteger a = BigInteger.valueOf(1234567890);
BigDecimal b = BigDecimal.valueOf(10000.234567891111111);
a=a.multiply(BigInteger.valueOf(11111111));
a=a.multiply(BigInteger.valueOf(11111111));
a=a.multiply(BigInteger.valueOf(11111111));
a=a.multiply(BigInteger.valueOf(11111111));
a=a.multiply(BigInteger.valueOf(11111111));
a=a.multiply(BigInteger.valueOf(11111111));
a=a.multiply(BigInteger.valueOf(11111111));
a=a.multiply(BigInteger.valueOf(11111111));
a=a.multiply(BigInteger.valueOf(11111111));
a=a.multiply(BigInteger.valueOf(11111111));
a=a.multiply(BigInteger.valueOf(11111111));
a=a.multiply(BigInteger.valueOf(11111111));
BigDecimal c = BigDecimal.valueOf(10001111111.2345678911111111111);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
输出结果:
输出结果为大数