2009-09-14 30 views
9

我看不到Math.Round的结果。舍入到即使在C#

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

据我了解MidpointRounding.ToEven,千分之五的位置应该会导致输出为99.96。这不是这种情况吗?

我甚至尝试这一点,但它返回99.97,以及:

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

我缺少什么

谢谢!

+4

所以你说的是,你想要它___到一个数字是_远离_?这是“四舍五入”的一个奇怪的定义。 – 2009-09-14 18:13:25

+1

这就是银行家对你的四舍五入。难怪我们在这个混乱;-) – 2009-09-14 18:26:14

+4

不,这不是银行家的四舍五入。银行家的四舍五入是当你选择四舍五入时,当两个选择同样遥远*。你不处于两种选择同样遥远的情况。其中一个比另一个更近,而你想选择更远的那个。 – 2009-09-14 22:35:46

回答

24

你实际上不在中点。 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); 
} 
8

它如果你在中点本身,则轮数为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 
>>> 
+1

使用IronPython的+1。让我微笑。 – 2009-09-14 18:40:59

+0

@Vinay,抱歉我的编辑错了.. – 2009-09-14 19:00:20

0

中点舍入是lo只有在两个案例之间的价值为0的情况下才提出。

在你的情况下,它不是“5”,它是“535 ...”,所以它比中点更大,例程更多.96。为了得到你期望的行为,你需要trunctate到第三个小数点,然后使用MidpointRounding.ToEven。

4

MidpointRounding值只有进场时,你试图圆其至少显著位正好是5换句话说一个值,该值必须是99.965得到您想要的结果。由于这里不是这种情况,因此您只是简单地观察标准舍入机制。有关更多信息,请参阅MSDN page

3

下面是摆脱一些关于这个问题光结果:

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.

0

Math.Round“舍小数值的指定的小数位数。“当时轮数为99.96500000,2轮为99.96和99.96500001至99.67。它提高了整个价值。

0

如果是我,我不会使用Math.Round(),因为这不是你要完成的。

这是我会做:

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

哪个更容易阅读和更多的是一种数学方法的。
我乘以100的数字,现在我有9996.535789
然后将它与舍入区别开来,返回最接近数字的最小整数,得到9996
然后我除以100以获得所需的99.96

P.S.
楼层天花板相反,它返回最接近该数字的最大整数。
因此,9996.535789的上限为9997
两者都不同于四舍五入到无小数点,实际上返回最接近整数的数字,不管它是小还是大 - 取其最接近的;这就是为什么当你使用舍入时你得到了99.97