Math.Round 小数点
我正在运行这段代码:
decimal d = 1.45M;
Console.WriteLine((System.Math.Round(d,0,MidpointRounding.AwayFromZero).ToString()));
这里我期望输出为 2,因为 1.45 当四舍五入到第一个小数位时将是 1.5,而当下一个四舍五入到小数点后 0 位时应该是 2。
但是,我得到的答案是 1。
我的假设是正确的?如果是这样,这是 Math.Round 的错误吗?
I am running this code:
decimal d = 1.45M;
Console.WriteLine((System.Math.Round(d,0,MidpointRounding.AwayFromZero).ToString()));
Here I expect the output to be 2 because 1.45 when rounded to 1st decimal place will be 1.5 which when next rounded to 0 decimal places should be 2.
However, I am getting the answer as 1.
Is my assumption correct? If so, is this a bug with Math.Round?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,这不是一个错误。您的逻辑讨论了两次舍入 - 但您只调用了一次
Round
。 1.45 小于 1 和 2 之间的中点 (1.5),因此它向下舍入为 1。如果您希望代码遵循您的逻辑,您可以这样做:
除非您指定您想要两个阶段尽管(如上所述).NET 只会完成四舍五入的操作。
No, it's not a bug. Your logic talks about rounding twice - but you've only got a single call to
Round
. 1.45 is less than the midpoint between 1 and 2 (1.5) so it's rounded down to 1.If you want the code to follow your logic, you can do this:
Unless you specify that you want two phases of rounding though (as above) .NET will just do the one.
您不能一位一位一位地进行“舍入”操作!这里你说:
这是不正确的,这里1.45四舍五入到0位,你只需要检查0.4。
You can't do 'round' action one digit by one digit! Here you say:
It's not correct, here 1.45 rounded to 0 digits, you need to check .4 only.
你的理解是不正确的。
您指定的小数值为 0,因此提供的值将四舍五入为整数值。
来自MSDN“如果d中由decimals参数表示的小数位右侧第一位数字的值为5,则小数位上的数字如果是奇数则向上舍入,如果是偶数则单独保留”
作为小数点右侧的第一个值为 4 而不是 5,则返回的值为 1。
如果小数点值为 1.55,则答案将为 2。
如果小数点值为 2.55,则答案将为 2还有!
当您指定中点舍入行为时,这将被更改,但是当您要求舍入与小数=0一起工作时,它只会检查小数点后的第一位数字。
事实上,如果您指定了decimals=1,如
“那么您的答案将是1.4”,因为它会检查小数点后的第二位数字是否对第一个数字进行四舍五入。
Your understanding is incorrect.
You have specified a decimals value of 0 therefore the value supplied will be rounded to an integer value.
From MSDN "If the value of the first digit in d to the right of the decimal position represented by the decimals parameter is 5, the digit in the decimals position is rounded up if it is odd or left alone if it is even"
As the first value to the right of the decimal point is 4 and not five then the value returned is 1.
If the decimal value had been 1.55 then the answer would have been 2.
If the decimal value had been 2.55 then the answer would have been 2 as well!
As you are specifying the midpoint rounding behaviour then this will be altered, but you as you are asking the round to work with decimals=0 it will only check the first digit after the decimal point.
Infact if you specified decimals=1 as in
Then your answer would be 1.4 as it checks the second digit after the decimal point for rounding of the first.