This question already has answers here:
Is floating point math broken?
                                
                                    (31个答案)
                                
                        
                                5年前关闭。
            
                    
我在C#中遇到舍入问题。我想将计算结果四舍五入到4个小数(远离零)。如果我使用Math.Round(variable,...),它会四舍五入,如果我手动输入结果,它会四舍五入..我不知道为什么。

我究竟做错了什么?以下代码的结果是:
取整:591.24575 591.2457-591.2458

double number1 = 1136.81;
double number2 = 4.00;
double number3 = 2182.257;
double result = (number1 * number2 - number3) / 4;
Console.WriteLine("Rounded: " +result+" " + Math.Round(result, 4, MidpointRounding.AwayFromZero) + " - " + Math.Round(591.24575, 4, MidpointRounding.AwayFromZero));
Console.ReadLine();

最佳答案

如果使用我的DoubleConverter,则可以看到result的确切值:

Console.WriteLine(DoubleConverter.ToExactString(result));


打印:

591.2457499999999299689079634845256805419921875


...四舍五入到小数点后四位时四舍五入为591.2457。当您仅打印result时,它将打印它已经四舍五入到小数点后的位数,如果然后(在心理上)四舍五入到4 DP,这会影响结果。

您可以看到它没有二进制浮点的任何“正常”奇数。考虑以下代码:

decimal exact = 1.2345m;
decimal rounded2 = Math.Round(exact, 2, MidpointRounding.AwayFromZero);
decimal rounded3 = Math.Round(exact, 3, MidpointRounding.AwayFromZero);
decimal rounded3Then2 = Math.Round(rounded3, 2, MidpointRounding.AwayFromZero);
Console.WriteLine(rounded2); // 1.23
Console.WriteLine(rounded3); // 1.235
Console.WriteLine(rounded3Then2); // 1.24


在您的代码中,您实际上并没有执行“两个舍入”操作-但是您在头脑中这样做是通过获取result(591.24575)的打印值,并假设可以准确地将其取整。

关于c# - 在C#中舍入错误? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25531603/

10-12 18:45