C# 双精度数除法时的精度损失

发布于 2024-09-06 13:13:39 字数 723 浏览 1 评论 0原文

下面的函数传递一个字符串“1004233”并打印以下输出:
D1 = 1.004233
D2 = 0.00423299999999993
D3 = 4232.99999999993
D4 = 4232

我需要 D4 来打印 4233 而不是 4232。我如何阻止这种精度损失的发生?

public string someFunc(String s){
        string retval = "0";
        try{
            int id = int.Parse(s);
            double d = (double)id / (double)1000000;
            Console.WriteLine("D1 = " + d);
            d = d - Math.Truncate(d);
            Console.WriteLine("D2 = " + d);
            d = d * (double)1000000;
            Console.WriteLine("D3 = " + d);
            retval = "" + Math.Truncate(d);
            Console.WriteLine("D4 = " + retval);
        }catch(Exception ex){}
        return retval;
}

The function bellow is passed a string "1004233" and prints the following output:

D1 = 1.004233
D2 = 0.00423299999999993
D3 = 4232.99999999993
D4 = 4232

I need D4 to print 4233 and not 4232. How do i stop this precision loss from happening?

public string someFunc(String s){
        string retval = "0";
        try{
            int id = int.Parse(s);
            double d = (double)id / (double)1000000;
            Console.WriteLine("D1 = " + d);
            d = d - Math.Truncate(d);
            Console.WriteLine("D2 = " + d);
            d = d * (double)1000000;
            Console.WriteLine("D3 = " + d);
            retval = "" + Math.Truncate(d);
            Console.WriteLine("D4 = " + retval);
        }catch(Exception ex){}
        return retval;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只为一人 2024-09-13 13:13:39

这是标准浮点问题

请改用十进制
尽管十进制也没有无限精度,但它们是以 10 为基数实现的,因此它们会给您期望的结果。

This is the standard floating-point question.

Use a decimal instead.
Although decimals also don't have infinite precision, they are implemented in base 10, so they will give you the results you expect.

弥繁 2024-09-13 13:13:39

使用十进制算术而不是浮点(双精度)。更多信息请参见:

Use decimal arithmetic instead of floating-point (double). More information to be found:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文