当前位置:网站首页>使用BigDecimal的坑
使用BigDecimal的坑
2022-07-07 07:10:00 【Keeling1720】
BigDecimal的坑
BigDecimal常被我们用于计算一些需要精确计算的场景,例如金额的计算。但是,BigDecimal也有很多不为人知的坑。下面,我们就来简单介绍几个常见的坑。
1、使用valueOf() 替代new BigDecimal
public static void main(String[] args) {
BigDecimal bigDecimal1 = new BigDecimal(0.01);
BigDecimal bigDecimal2 = BigDecimal.valueOf(0.01);
System.out.println(bigDecimal1);
System.out.println(bigDecimal2);
}
输出结果是:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mwyC8uaE-1656647473350)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1656565943063.png)]](/img/dd/d9b2e37afaff0e323516dc0332dba2.png)
可以看到,直接new BigDecimal传入0.01的时候,由于0.01这个数字计算机是无法精确表示的,导致传入到BigDecimal中就已经丢失精度。最终输出的结果就有存在误差。而valueOf 则不同,他的底层将Double转化为了String,确保了他的精度不会丢失。
public static BigDecimal valueOf(double val) {
return new BigDecimal(Double.toString(val));
}
总结:尽量使用字符串形式来构造BigDecimal对象,如果实在不行,那么也请使用BigDecimal.valueOf()方法将值进行转换,以此确保我们的精度。
2、使用compareTo而不是equals进行比较
public static void main(String[] args) {
BigDecimal bigDecimal1 = new BigDecimal("1.0");
BigDecimal bigDecimal2 = new BigDecimal("1.00");
System.out.println(bigDecimal2.equals(bigDecimal1));
System.out.println(bigDecimal2.compareTo(bigDecimal1));
}
运行结果:
运行结果中,使用equals对比两个BigDecimal的值会等于false,因为BigDecimal的equals会比较两个数字的精度,而compareTo方法只会比较两个数的大小。
总结:使用compareTo而不是equals比较两个BigDecimal的值。
3、BigDecimal并不是无限精度
public static void main(String[] args) {
BigDecimal bigDecimal1 = new BigDecimal("1.0");
BigDecimal bigDecimal2 = new BigDecimal("3.0");
bigDecimal1.divide(bigDecimal2);
}
运行结果如下:
这是因为,1 / 3 等于 无限循环小数(0.33333… )。这个时候,我们就必须告诉JVM,我们不需要最精确的结果。修改代码为:
public static void main(String[] args) {
BigDecimal bigDecimal1 = new BigDecimal("1.0");
BigDecimal bigDecimal2 = new BigDecimal("3.0");
System.out.println(bigDecimal1.divide(bigDecimal2, RoundingMode.HALF_UP));
}
运行结果:

4、转化为String要用对方法
public static void main(String[] args) {
BigDecimal bigDecimal = BigDecimal.valueOf(12345678902132123113213.12345678912345678);
//必要时,使用科学计数法
System.out.println(bigDecimal.toString());
//不使用科学计数法
System.out.println(bigDecimal.toPlainString());
//工程计算中经常使用的记录数字的方法,类似科学计数法,但要求是10的幂必须是3的倍数
System.out.println(bigDecimal.toEngineeringString());
}
运行结果:
总结:
- toString():如果必要的时候,使用科学计数法。
- toPlainString():不使用科学计数法
- toEngineeringString():工程计算中经常使用的记录数字的方法,类似科学计数法,但要求是10的幂必须是3的倍数
边栏推荐
- La différence entre viewpager 2 et viewpager et la mise en œuvre de la rotation viewpager 2
- iNFTnews | 时尚品牌将以什么方式进入元宇宙?
- JS judge whether checkbox is selected in the project
- 如何使用clipboard.js库实现复制剪切功能
- 2020浙江省赛
- [4g/5g/6g topic foundation-146]: Interpretation of white paper on 6G overall vision and potential key technologies-1-overall vision
- Sqlplus garbled code problem, find the solution
- How to speed up video playback in browser
- liunx命令
- 数据库多表关联查询问题
猜你喜欢

Netease Cloud Wechat applet

JS逆向教程第一发

PLC信号处理系列之开关量信号防抖FB

Unity shader (learn more about vertex fragment shaders)

【frida实战】“一行”代码教你获取WeGame平台中所有的lua脚本

第一讲:寻找矩阵的极小值

Diffusion模型详解

Vs2013 generate solutions super slow solutions

Information Security Experiment 1: implementation of DES encryption algorithm

STM32 and motor development (from stand-alone version to Networking)
随机推荐
What development models did you know during the interview? Just read this one
第一讲:寻找矩阵的极小值
iNFTnews | 时尚品牌将以什么方式进入元宇宙?
How to become a senior digital IC Design Engineer (5-3) theory: ULP low power design technology (Part 2)
软件建模与分析
IIS faked death this morning, various troubleshooting, has been solved
liunx命令
Impression notes finally support the default markdown preview mode
Dynamics 365online applicationuser creation method change
How will fashion brands enter the meta universe?
Information Security Experiment 4: implementation of IP packet monitoring program
PLC信号处理系列之开关量信号防抖FB
PostgreSQL reports an error when creating a trigger,
Vs2013 generate solutions super slow solutions
ComputeShader
Network request process
JMeter JDBC batch references data as input parameters (the simplest method for the whole website)
(3/8) method parameters of improper use of enumeration (2)
信息安全实验三 :PGP邮件加密软件的使用
H5 web player easyplayer How does JS realize live video real-time recording?