首页 > 基础资料 博客日记
Java中浮点数运算存在的精度问题以及解决方法
2024-09-27 21:00:04基础资料围观351次
观察以下一段代码,相信小朋友都可以一眼看出答案,但是计算机给出的答案是这样吗?
public class TestDouble {
public static void main(String args[]) {
System.out.println("0.05 + 0.01 = " + (0.05 + 0.01));
System.out.println("1.0 - 0.42 = " + (1.0 - 0.42));
System.out.println("4.015 * 100 = " + (4.015 * 100));
System.out.println("123.3 / 100 = " + (123.3 / 100));
}
}
完整运行结果:
想不到吧,最后的运行结果居然是这样一堆奇奇怪怪的小数
解答:这是因为因为浮点数在计算机内部是以二进制形式存储的,某些十进制小数无法精确表示。因此,直接运算可能会导致不精确的结果。
解决方法
这里给出三种简单的处理方法
方法一:四舍五入
使用Math.round()对结果进行四舍五入
以上述代码为例进行修改:
public class TestDouble { public static void main(String args[]) { System.out.println("0.05 + 0.01 = " + Math.round((0.05 + 0.01)*100.0)/100.0); System.out.println("1.0 - 0.42 = " + Math.round((1.0 - 0.42)*100.0)/100.0); System.out.println("4.015 * 100 = " + Math.round((4.015 * 100)*100.0)/100.0); System.out.println("123.3 / 100 = " + Math.round((123.3 / 100)*1000.0)/1000.0); } }
结果如下图:
注意:直接使用Math.round时只保留整数
方法二:使用BigDecimal 类
`import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalRoundExample {
public static void main(String[] args) {
double num = 0.5 + 0.1;
BigDecimal bd = new BigDecimal(Double.toString(num));
BigDecimal x = bd.setScale(2, RoundingMode.HALF_UP);//2表示要保留的小数位数
System.out.println(x);
}
}
`
结果:
0.06
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:
相关文章
最新发布
- springboot~3.x项目中使用集成测试
- Java测试类、工具类与JavaBean对比解析
- SpringBoot-日志
- springboot~http2的支持
- 解疑释惑 - 日志体系之 slf4j + logback 组合(一)
- Web server failed to start. Port 8080 was already in use. 端口被占用
- Springboot 项目配置多数据源
- 伙伴匹配系统(移动端 H5 网站(APP 风格)基于Spring Boot 后端 + Vue3 - 05
- 剑指offer-23、搜索⼆叉树的后序遍历序列
- 一个表示金额的数字是 100000000L,这是多少米?