BigInteger类和BigDecimal类
BigInteger类基本介绍
-
BigInteger 适合保存比较大的整型
-
在对 BigInteger 类的变量进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /
public class test {
public static void main(String[] args) {
BigInteger bigInteger = new BigInteger("234999999999999999999999999999");
BigInteger bigInteger1 = new BigInteger("100");
BigInteger add = bigInteger.add(bigInteger1); //加
BigInteger subtract = bigInteger.subtract(bigInteger1);//减
BigInteger multiply = bigInteger.multiply(bigInteger1);//乘
BigInteger divide = bigInteger.divide(bigInteger1);//除
System.out.println(add);
System.out.println(subtract);
System.out.println(multiply);
System.out.println(divide);
}
}
BigDecimal类基本介绍
-
BigDecimal 适合保存精度更高的浮点型(小数)
-
在对 BigDecimal类的变量进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /
-
在调用 divide() 方法时,可能会抛出异常 ArithmeticException (算术结果为无限循环小数,即除不尽),只需要在调用divide() 方法时,指定精度即可。
-
指定精度BigDecimal.ROUND_CEILING ,如果有无限循环小数,就会保留分子的精度
public class test {
public static void main(String[] args) {
BigDecimal bigDecimal = new BigDecimal("1223.111111111199999999999999998");
BigDecimal bigDecimal2 = new BigDecimal("3");
BigDecimal add = bigDecimal.add(bigDecimal2);
BigDecimal subtract = bigDecimal.subtract(bigDecimal2);
BigDecimal multiply = bigDecimal.multiply(bigDecimal2);
BigDecimal divide = bigDecimal.divide(bigDecimal2,BigDecimal.ROUND_CEILING);
System.out.println(add);
System.out.println(subtract);
System.out.println(multiply);
System.out.println(divide);
}
}