BigInteger类
很小概率的情况,long类型可能会出现不够用,因此便诞生了BigInteger这个类,此类继承自Number。
此类没有范围限制,但缺点是较long速度慢。
定义和例子:
BigInteger i1 = new BigInteger("1234567890");
BigInteger i2 = new BigInteger("12345678901234567890");
BigInteger sum = i1.add(i2); // 12345678902469135780
BigInteger和其他的Integer类和Long类一样,继承自Number,因此也有其对应的转换为基本类型的方法
- 转换为byte:byteValue()
- 转换为short:shortValue()
- 转换为int:intValue()
- 转换为long:longValue()
- 转换为float:floatValue()
- 转换为double:doubleValue()
如果需要准确地转换成基本类型,可以使用intValueExact()、longValueExact()等方法
超出范围转换会报错。
BigDecimal类
BigDecimal类和BigInteger类相似,它可以表示一个任意大小且精度完全准确的浮点数。
比较:用compareTo()方法来比较。不要使用equals()
BigDecimal中的方法:
scale()表示小数位数
stripTrailingZeros()方法,可以将一个BigDecimal格式化为一个相等的,但去掉了末尾0的BigDecimal