BigInteger和BigDecimal
我们知道,基本数据类型所能保存的数据大小和精度是有范围的,那么在处理一些很大或很高精度的数据时就不能使用了
所以java提供了两个类,来处理很大的数据--------BigInteger和BigDecimal
用这两个个类来处理很大的数据时,加减乘除都不能直接操作,必须调用这两个类的方法,以下分别是两个类的例子
public static void main(String[] args) { BigInteger bigInteger = new BigInteger("9999999999999999999999999"); BigInteger bigInteger1 = new BigInteger("9999999999999999999999999"); BigInteger bigInteger2 = bigInteger.add(bigInteger1); System.out.println(bigInteger2); } 运行结果 19999999999999999999999998
public static void main(String[] args) { BigDecimal bigDecimal = new BigDecimal("1.222222222222222222222222"); BigDecimal bigDecimal1 = new BigDecimal("3"); BigDecimal divide = bigDecimal.divide(bigDecimal1); System.out.println(divide); } 运行结果 //抛出了算术异常 //正确使用如下 public static void main(String[] args) { //BigDecimal必须传精度进去,不然遇到除不尽的时候就会抛出算术异常 BigDecimal bigDecimal = new BigDecimal("1.222222222222222222222222"); BigDecimal bigDecimal1 = new BigDecimal("3"); BigDecimal divide = bigDecimal.divide(bigDecimal1,BigDecimal.ROUND_CEILING);
//BigDecimal.ROUND_CEILING)就是一种精度模式,具体去看源码 System.out.println(divide); } 运行结果 0.407407407407407407407408