java入门-----整数的大运算类
整数的大运算类 – BigInteger
将大整数转换为字符串运算
BigInteger big1 = new BigInteger("987654321123654987654321123654");//int类型无法运算这么大的值
BigInteger big2 = new BigInteger("987654321123654987654321123654");//int类型无法运算这么大的值
BigInteger add = big1.add(big2);//加法
System.out.println(add);
BigInteger subtract = big1.subtract(big2);//减法
System.out.println(subtract);
BigInteger multiply = big1.multiply(big2);//乘法
System.out.println(multiply);
BigInteger divide = big1.divide(big2);//除法
System.out.println(divide);
1975308642247309975308642247308
0
975461058034227806755274380168687127374657657855833158311716
1
小数类型的大数值运算类 – BigDecimal
double类型计算小数会出现偏差
double a=0.5;
double b=0.4;
System.out.println("a-b="+(a-b);//double类型计算小数会出现偏差
a-b=0.09999999999999998
使用大数值运算类计算小数不会出现偏差
BigDecimal big1 = new BigDecimal("0.5");
BigDecimal big2 = new BigDecimal("0.4");
BigDecimal add = big1.add(big2);//加法
System.out.println(add);
BigDecimal subtract = big1.subtract(big2);//减法
System.out.println(subtract);
BigDecimal multiply = big1.multiply(big2);//乘法
System.out.println(multiply);
BigDecimal divide = big1.divide(big2);//除法
System.out.println(divide);
0.9
0.1
0.20
1.25
注意:小数除法一定要设置保留几位小数 和 进制模式
BigDecimal big1 = new BigDecimal("10");
BigDecimal big2 = new BigDecimal("3");
//除法
//-------big2是除数-----2是保留两位小数------BigDecimal.ROUND_HALF_UP意思是四舍五入
BigDecimal divide = big1.divide(big2, 2, BigDecimal.ROUND_HALF_UP);
System.out.println(divide);
3.33