BigDecimal amount1 = new BigDecimal("10.50");
BigDecimal amount2 = new BigDecimal("5.25");
// 加法运算
BigDecimal sum = amount1.add(amount2);
System.out.println("Sum: " + sum);
// 减法运算
BigDecimal difference = amount1.subtract(amount2);
System.out.println("Difference: " + difference);
// 乘法运算
BigDecimal product = amount1.multiply(amount2);
System.out.println("Product: " + product);
// 除法运算
BigDecimal quotient = amount1.divide(amount2, 2, BigDecimal.ROUND_HALF_UP);
System.out.println("Quotient: " + quotient);
输出结果
Sum: 15.75
Difference: 5.25
Product: 55.1250
Quotient: 2.00
在进行除法运算时,我们指定了保留小数点后两位,并使用 BigDecimal.ROUND_HALF_UP 进行四舍五入
更多【java-java计算】相关视频教程:www.yxfzedu.com