大数字处理类
大数字处理类的作用:
大数字处理类可以实现海量数字的计算
两种大数字处理类及其构造:
BigInteger 类构造:public BigInteger(String val);
BigDecimal 类构造:public BigDecimal(String val);
大数字类
常用方法:
BigInteger big = new BigInteger("123123");
BigInteger num = new BigInteger("123");
System.out.println("加法:" + big.add(num)); // 加法:123244
System.out.println("减法:" + big.subtract(num));// 减法:123002
System.out.println("乘法:" + big.multiply(num));// 乘法:14897883
System.out.println("除法:" + big.divide(num));// 除法:1017
for (BigInteger bigInteger : big.divideAndRemainder(num)) {
System.out.print(bigInteger+"、");
}// 1017、66、 结果为商和余数
BigDecimal与BigInteger用法基本相同,但BigDecimal是浮点数,所以涉及到了精度问题
BigDecimal的四舍五入:
/**
* 实现数据的四舍五入操作
* @param num 四舍五入数据
* @param scale 保留几位小数
* @return 保留小数点后的数据
*/
private static BigDecimal round(BigDecimal num ,int scale) {
return num.divide(new BigDecimal(1.0), scale, RoundingMode.HALF_UP);
}
Math 与大数字处理类的区别
BigDecimal 与 Math 相比,Math 的处理由于使用的都是基本数据类型,所以性能高于大数字处理类 BigDecimal
PS:知识总结与阿里培训中心