前面说过了浮点类型的值不能用于不能出现舍入误差的计算中,如计算几本书的总金额,有可能会出现舍入误差,这是不允许的,所以Java提供了java.math包中的两个类,BigInteger和BigDecimal
- BigInteger可以可以处理任意长度的整数序列的数值,实现了,任意精度的整数运算,
- BigDecimal可以处理任意长度的浮点数序列的数值,实现了任意精度的浮点数运算,
但是不能使用 + - * / 这类符号进行运算,反而要使用这两个类的方法来进行运算,
BigInteger类中的常用方法如下:
- BigInteger add(BigInteger other) ,将两个大整数相加
- BigInteger subtract(BigInteger other) 将两个大整数相减
- BigInteger multiply(BigInteger other) 将两个大整数相乘
- BigInteger divide(BigInteger other) 将两个大整数相除
- BigInteger mod(BigInteger other) 返回将两个大整数相除之后的余数
- int compareTo(BigInteger other) 若这个大整数于other相等返回0,若小于它返回-1 否则 0
- Static BigInteger valueOf(long x);返回一个值为x的大整数
看一个例子:
int a = Integer.MAX_VALUE;
System.out.println(a * a); // 1,溢出了
BigInteger integer = BigInteger.valueOf(Integer.MAX_VALUE);
System.out.println(integer.multiply(integer)); // 4611686014132420609,没有溢出
BigDecimal类中的常用方法如下:
- add(other)
- subtract(other)
- multiply(other)
- divide( other) 注意这个方法需要为其提供一个舍入策略,如RoundMode.HALF_UP四舍五入
- compareTo(other)
- valueOf(long x)
- valueOf(long x ,int scale),返回x/10的scale次方,
看一个例子:
System.out.println(2.0 - 1.1); // 0.8999999999999999
System.out.println(BigDecimal.valueOf(2.0).subtract(BigDecimal.valueOf(1.1))); // 0.9
注意:Java确实为字符串重载了 + ,但是没有为其他类型重载 +
浙公网安备 33010602011771号