您现在的位置是: 首页 > 后端开发 > 编程开发
Java BigDecimal 加减乘除计算示例
2023-03-27 【后端开发】
简介
下面是Java中使用BigDecimal进行加减乘除计算的示例代码
import java.math.BigDecimal;
public class BigDecimalExample {
public static void main(String[] args) {
// 初始化BigDecimal对象
BigDecimal num1 = new BigDecimal("10.23");
BigDecimal num2 = new BigDecimal("3.45");
// 加法运算
BigDecimal sum = num1.add(num2);
System.out.println("和:" + sum);
// 减法运算
BigDecimal difference = num1.subtract(num2);
System.out.println("差:" + difference);
// 乘法运算
BigDecimal product = num1.multiply(num2);
System.out.println("积:" + product);
// 除法运算
BigDecimal quotient = num1.divide(num2, 2, BigDecimal.ROUND_HALF_UP);
System.out.println("商:" + quotient);
}
}
在上面的示例代码中,我们首先通过new BigDecimal()方法初始化了两个BigDecimal对象num1和num2,然后分别进行了加、减、乘、除四种运算,并将结果打印输出。
需要注意的是,在除法运算时,我们使用了divide()方法,并指定了精度和舍入方式。具体来说,第一个参数指定了除数,第二个参数指定了保留的小数位数,第三个参数指定了舍入方式,这里我们使用的是四舍五入。
很赞哦! (0)
相关文章
- DataGrip 防止全表更新或删除限制
- idea 提示 @Transactional self-invocation (in effect, a method within the target object calling another method of the target object) does not lead to an actual transaction at runtime 问题原因
- IntelliJ IDEA 2023.1 发布,新UI 改进
- The bean 'xxxx.FeignClient' could not be registered. A bean with that name has already been defined and overriding is disabled. 问题原因
- Syntax Error: `asyncRouterMap` has already been exported. Exported identifiers must be unique. 错误原因
- MySQL 备份操作
- 控制台出现 was not registered for synchronization because DataSource is not transactional 是什么问题
- curl Empty reply from server 原因及解决方案
- Java BigDecimal 加减乘除计算示例
- docker容器里面没有vim解决方案
点击排行
- DataGrip 防止全表更新或删除限制
- idea 提示 @Transactional self-invocation (in effect, a method within the target object calling another method of the target object) does not lead to an actual transaction at runtime 问题原因
- IntelliJ IDEA 2023.1 发布,新UI 改进
- The bean 'xxxx.FeignClient' could not be registered. A bean with that name has already been defined and overriding is disabled. 问题原因
- Syntax Error: `asyncRouterMap` has already been exported. Exported identifiers must be unique. 错误原因
- MySQL 备份操作
- 控制台出现 was not registered for synchronization because DataSource is not transactional 是什么问题
- curl Empty reply from server 原因及解决方案
- Java BigDecimal 加减乘除计算示例
- docker容器里面没有vim解决方案
猜你喜欢
- DataGrip 防止全表更新或删除限制
- idea 提示 @Transactional self-invocation (in effect, a method within the target object calling another method of the target object) does not lead to an actual transaction at runtime 问题原因
- IntelliJ IDEA 2023.1 发布,新UI 改进
- The bean 'xxxx.FeignClient' could not be registered. A bean with that name has already been defined and overriding is disabled. 问题原因
- Syntax Error: `asyncRouterMap` has already been exported. Exported identifiers must be unique. 错误原因
- MySQL 备份操作
- 控制台出现 was not registered for synchronization because DataSource is not transactional 是什么问题
- curl Empty reply from server 原因及解决方案
- Java BigDecimal 加减乘除计算示例
- docker容器里面没有vim解决方案