目录
1.BigInteger类
1.BigInteger类
当需要很大的整数,long不够用时,可以使用BigInteger类来搞定
(1).在对BigInteger 进行加减乘除时,需要使用对应的方法
(2).可以创建一个要操作的BigInteger 然后进行操作
例题如下:
import java.math.BigInteger;
public class BigInteger_ {
public static void main(String[] args) {
//当需要很大的整数,long不够用时,可以使用BigInteger类来搞定
BigInteger bigInteger = new BigInteger("99999999999999999999999999999999999");
BigInteger bigInteger2 = new BigInteger("1111111111");
System.out.println(bigInteger);
//(1).在对BigInteger 进行加减乘除时,需要使用对应的方法
//(2).可以创建一个要操作的BigInteger 然后进行操作
//加
BigInteger add=bigInteger.add(bigInteger2);
System.out.println(add);
//减
BigInteger subtract=bigInteger.subtract(bigInteger2);
System.out.println(subtract);
//乘
BigInteger multiply=bigInteger.multiply(bigInteger2);
System.out.println(multiply);
//除
BigInteger divide=bigInteger.divide(bigInteger2);
System.out.println(divide);
}
}
运行结果如下:
99999999999999999999999999999999999
100000000000000000000000001111111110
99999999999999999999999998888888888
111111111099999999999999999999999998888888889
90000000009000000000900000
2.BigDecimal类
当我们需要保存精度很高的数时,double不够,可以使用BigDecimal类
(1).在对BigInteger 进行加减乘除时,需要使用对应的方法
(2).可以创建一个要操作的BigInteger 然后进行操作
例题如下:
import java.math.BigDecimal;
public class BigDecimal1 {
public static void main(String[] args) {
//当我们需要保存精度很高的数时,double不够,可以使用BigDecimal类
BigDecimal bigDecimal = new BigDecimal("199.999999999999999999999999999");
BigDecimal bigDecimal2 = new BigDecimal("1.1");
System.out.println(bigDecimal);
//(1).在对BigInteger 进行加减乘除时,需要使用对应的方法
//(2).可以创建一个要操作的BigInteger 然后进行操作
//加
System.out.println(bigDecimal.add(bigDecimal2));
//减
System.out.println(bigDecimal.subtract(bigDecimal2));
//乘
System.out.println(bigDecimal.multiply(bigDecimal2));
//除
//System.out.println(bigDecimal.divide(bigDecimal2)可能会抛出异常ArithmticException
//调用diVide方法时,指定精度即可,BigDecimal.ROUND_CEILING
//如果有无限循环的小数,就会保留分子的精度
System.out.println(bigDecimal.divide(bigDecimal2,BigDecimal.ROUND_CEILING));
}
}
运行结果如下:
199.999999999999999999999999999
201.099999999999999999999999999
198.899999999999999999999999999
219.9999999999999999999999999989
181.818181818181818181818181818