我没有看到 Math.Round 的预期结果。

return Math.Round(99.96535789, 2, MidpointRounding.ToEven); // returning 99.97

据我了解 MidpointRounding.ToEven,千分位位置的 5 应该导致输出为 99.96。难道不是这样吗?

我什至尝试过这个,但它也返回了 99.97:

return Math.Round(99.96535789 * 100, MidpointRounding.ToEven)/100;

我缺少什么

谢谢!

有帮助吗?

解决方案

你实际上并不是中点。 MidpointRounding.ToEven 表示如果您的号码为 99.965 ,即99.96500000 [等],,您将得到99.96。由于您传递给Math.Round的数字高于此中点,因此它正在四舍五入。

如果您希望将您的号码舍入到99.96,请执行以下操作:

// this will round 99.965 down to 99.96
return Math.Round(Math.Truncate(99.96535789*1000)/1000, 2, MidpointRounding.ToEven);

嘿,这是一个方便的小功能来完成上述一般情况:

// This is meant to be cute;
// I take no responsibility for floating-point errors.
double TruncateThenRound(double value, int digits, MidpointRounding mode) {
    double multiplier = Math.Pow(10.0, digits + 1);
    double truncated = Math.Truncate(value * multiplier) / multiplier;
    return Math.Round(truncated, digits, mode);
}

其他提示

如果你在中点本身,它只会达到99.96,即99.965:

C:\temp>ipy
IronPython 2.6 Beta 2 (2.6.0.20) on .NET 2.0.50727.4927
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> from System import Math, MidpointRounding
>>> Math.Round(99.9651, 2, MidpointRounding.ToEven)
99.97
>>> Math.Round(99.965, 2, MidpointRounding.ToEven)
99.96
>>> Math.Round(99.9649, 2, MidpointRounding.ToEven)
99.96
>>> Math.Round(99.975, 2, MidpointRounding.ToEven)
99.98
>>>

MidpointRounding 值仅在您尝试对最低有效数字正好为5的值进行舍入时才起作用。换句话说,该值必须为是 99.965 以获得您想要的结果。由于这不是这种情况,您只需观察标准的舍入机制。有关详细信息,请参阅 MSDN页面

以下是对该主题有所了解的结果:

Math.Round(99.96535789, 2, MidpointRounding.ToEven); // returning 99.97
Math.Round(99.965, 2, MidpointRounding.ToEven);      // returning 99.96
Math.Round(99.96500000, 2, MidpointRounding.ToEven); // returning 99.96

中点恰好是5 ...而不是535789,而不是499999。

只有当值介于两种情况之间时,才会查看中点舍入。

在你的情况下,它不是“5”,它是“535 ......”,所以它大于中点,并且例程为.96。为了得到你期望的行为,你需要转换到第三个小数点,然后使用MidpointRounding.ToEven进行回合。

Math.Round'将十进制值舍入到指定数量的小数位。当圆形99.96500000,2轮到99.96和99.96500001到99.67。它使整个值完整。

如果是我我不会用 Math.Round(), ,因为这不是您想要实现的目标。

这就是我要做的:

double num = 99.96535789;
double percentage = Math.Floor(100 * num) / 100;  

这更容易阅读,并且更像是一种数学方法。
我将这个数字乘以 100, , 我现在有 9996.535789.
然后对它进行取整,这与舍入明显不同,返回最接近该数字的最小整数,得到 9996.
然后我除以 100 以获得所需的 99.96.

附:
地面 是相反的 天花板, ,返回最接近该数字的最大整数。
所以,天花板 9996.5357899997.
两者都不同于 四舍五入 没有小数点,实际上返回最接近该数字的整数,无论​​它是小还是大——以最接近的为准;这就是你得到的原因 99.97 当你使用 四舍五入.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top