浅谈BigDecimal类型的加减乘除运算之Java
Java中BigDecimal类型的加减乘除运算add():加法, subtract():减法:, multiply():乘法; divide():除法,
1.简单的加减乘除运算
public class test {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("100");
BigDecimal num2 = new BigDecimal("200");
System.out.println("num1 = " + num1 + ",num2 = " + num2);
// num1 + num2
BigDecimal add = num1.add(num2);
System.out.println("num1 + num2 = " + add);
// num2 - num1
BigDecimal subtract = num2.subtract(num1);
System.out.println("num2 - num1 = " + subtract);
// num1 * mun2
BigDecimal multiply = num1.multiply(num2);
System.out.println("num1 * num2 = " + multiply);
// num2 /num1
BigDecimal divide = num2.divide(num1);
System.out.println("num2 / num1 = " + divide);
}
}
http://www.51testing.com/attachments/2023/05/15326880_202305261558001F9Fw.png
2.除法运算
小数点后面保留2位
public class test {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("5.99989");
BigDecimal num2 = new BigDecimal("2");
System.out.println("num1 = " + num1 + ",num2 = " + num2);
// num2 / num1 保留2位小数
BigDecimal divide1 = num1.divide(num2);
System.out.println("num1 / num2 = " + divide1);
BigDecimal divide2 = num1.divide(num2,2,BigDecimal.ROUND_HALF_UP);
System.out.println("num1 / num2(保留2位小数,四舍五入) = " + divide2);
}
}
ROUND_HALF_UP:四舍五入,即舍入部分大于等于0.5时进位,否则丢弃舍入部分。
ROUND_HALF_DOWN:五舍六入,即舍入部分大于0.5时进位,否则丢弃舍入部分。
http://www.51testing.com/attachments/2023/05/15326880_202305261558031tnzw.png
页:
[1]