Java技术之大数值
如果整型和浮点数的精度都不能满足需求,那么可以使用BigDecimal和BigInteger,这两个类可以处理任意长度数字序列的数值
BigInteger实现了任意精度的整数运算
BigDecimal实现了任意精度的浮点数运算
public static void main(String[] args) {
BigInteger bigInteger = BigInteger.valueOf(100);//整数可以转为大数值类型
System.out.println(bigInteger);
BigInteger bigInteger2 = BigInteger.valueOf(2);
System.out.println(bigInteger.add(bigInteger2));//相加,即 +
System.out.println(bigInteger.subtract(bigInteger2));//相减,即 -
System.out.println(bigInteger.multiply(bigInteger2));//相乘,即 *
System.out.println(bigInteger.divide(bigInteger2));//相除,即 /
System.out.println(bigInteger.mod(bigInteger2));//余数,即 %
if (bigInteger.compareTo(bigInteger2) > 0) {
System.out.println("bigInteger>=bigInteger2:" + bigInteger + ">" + bigInteger2);
} else if (bigInteger.compareTo(bigInteger2) < 0) {
System.out.println("bigInteger<bigInteger2:" + bigInteger + "<" + bigInteger2);
} else {
System.out.println("bigInteger=bigInteger2:" + bigInteger + "=" + bigInteger2);
}
}