[英]MidpointRounding.AwayFromZero
Why does below code returns 1299.49 ? 为什么下面的代码返回1299.49? According to msdn documentation it should give 1299.5.
根据msdn文档,应该给出1299.5。
Console.WriteLine(Math.Round( 1299.492, 2, MidpointRounding.AwayFromZero))
You are rounding to 2 decimal places, hence why 1299.49 is returned. 您将舍入到小数点后两位,因此为什么返回1299.49。
If you want it to be 1299.5, round to 1 decimal place. 如果希望为1299.5,则舍入到小数点后一位。
Console.WriteLine(Math.Round( 1299.492, 1, MidpointRounding.AwayFromZero))
From the documentation about AwayFromZero: 从有关AwayFromZero的文档中:
When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.
当一个数字位于其他两个数字的中间时,会将其舍入为最接近零的数字。
https://msdn.microsoft.com/en-us/library/system.midpointrounding(v=vs.110).aspx https://msdn.microsoft.com/zh-CN/library/system.midpointrounding(v=vs.110).aspx
You may be confused as to how this overload works. 您可能对这种重载的工作方式感到困惑。 According to MSDN on MidpointRounding :
根据MSDN在MidpointRounding上 :
When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.
当一个数字位于其他两个数字的中间时,会将其舍入为最接近零的数字。
In your case, 1299.492 is not halfway between 1229.49 and 1299.50, so MidpointRounding.AwayFromZero
doesn't even apply. 就您而言,1299.492不在1229.49和1299.50之间,因此
MidpointRounding.AwayFromZero
甚至不适用。
It looks like what you're actually trying to do is round up to the nearest 2 decimal places. 您实际要执行的操作似乎是四舍五入到小数点后两位。 In that case, you want something like this answer :
在这种情况下,您需要这样的答案 :
public static double RoundUp(double input, int places)
{
double multiplier = Math.Pow(10, Convert.ToDouble(places));
return Math.Ceiling(input * multiplier) / multiplier;
}
This rounds up to the specified decimal places by multiplying by 10^places
(100 if you need 2 places), calling Math.Ceiling
, and then dividing. 通过乘以
10^places
(如果需要2位, Math.Ceiling
100),将其Math.Ceiling
入为指定的小数位,然后调用Math.Ceiling
,然后除以。
This works: 这有效:
Console.WriteLine(RoundUp(1299.492, 2)); // 1299.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.