首页 > 基础资料 博客日记

Java中浮点数运算存在的精度问题以及解决方法

2024-09-27 21:00:04基础资料围观17

文章Java中浮点数运算存在的精度问题以及解决方法分享给大家,欢迎收藏Java资料网,专注分享技术知识

观察以下一段代码,相信小朋友都可以一眼看出答案,但是计算机给出的答案是这样吗?
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


文章来源:https://www.cnblogs.com/zyh-828/p/18434461/2024-9-27-01
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云