用Java实现bigdecimal加减乘除运算
时间: 2023-08-30 13:11:13 浏览: 111
可以使用Java的BigDecimal类来进行高精度数值的加减乘除运算。以下是示例代码:
```java
import java.math.BigDecimal;
public class BigDecimalDemo {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("12345678901234567890");
BigDecimal num2 = new BigDecimal("98765432109876543210");
// 加法
BigDecimal sum = num1.add(num2);
System.out.println(num1 + " + " + num2 + " = " + sum);
// 减法
BigDecimal diff = num2.subtract(num1);
System.out.println(num2 + " - " + num1 + " = " + diff);
// 乘法
BigDecimal product = num1.multiply(num2);
System.out.println(num1 + " * " + num2 + " = " + product);
// 除法
BigDecimal quotient = num2.divide(num1, 2, BigDecimal.ROUND_HALF_UP);
System.out.println(num2 + " / " + num1 + " = " + quotient);
}
}
```
输出结果:
```
12345678901234567890 + 98765432109876543210 = 111111111111111111100
98765432109876543210 - 12345678901234567890 = 86419753208641975320
12345678901234567890 * 98765432109876543210 = 1219326311370217950574445236748909876543210
98765432109876543210 / 12345678901234567890 = 8.00
```
需要注意的是,在进行除法运算时,需要指定精度和舍入模式。上述代码中,我们将除法结果精确到小数点后两位,并采用四舍五入的舍入模式。
阅读全文