小数 Math.Round 的问题显示不正确的舍入

Issue with Math.Round for decimals shows incorrect rounding

我在执行此操作时得到无效值 Math.Round(0.575, 2, MidpointRounding.AwayFromZero)

尝试进行中点舍入?

输入:Math.Round(0.575, 2, MidpointRounding.AwayFromZero) 预期:0.58 但得到 0.57

输入:Math.Round(-0.575, 2, MidpointRounding.AwayFromZero) 预期:-0.58 但得到 -0.57

输入:Math.Round(-0.865, 2, MidpointRounding.AwayFromZero) 预期:-0.87 并且输出与预期结果匹配为 -0.87

这里是快速 fiddle 尝试 https://dotnetfiddle.net/KdR8pN

能否尝试使用 decimal 类型而不是 double 类型?谢谢。

示例:https://docs.microsoft.com/en-us/dotnet/api/system.math.round?view=net-6.0#system-math-round(system-decimal-system-midpointrounding)

Decimal targetValue = -0.575m;
Decimal targetValue1 = 0.575m;
    
Console.Write(Math.Round(targetValue, 2, MidpointRounding.AwayFromZero) + Environment.NewLine);
Console.Write(Math.Round(targetValue1, 2, MidpointRounding.AwayFromZero)+ Environment.NewLine);

看看Why is 0.575 * 100 not same as 57.5?

问题是0.575不能精确表示为浮点数,而是使用最接近的浮点数0.57499999999999996。因此,它将始终向下舍入为 0.57。