C# 中从更高精度的数字舍入到小数点后两位
我如何在 C# 中舍入以下数字以获得以下结果。
值:500.0349999999
四舍五入到小数点后两位数后:500.04
我尝试过 Math.Round(Value,2, MidpointRounding.AwayFromZero);
//但它返回值 500.03 而不是 500.04
How would I round the following number in C# to obtain the following results.
Value : 500.0349999999
After Rounding to 2 digits after decimal : 500.04
I have tried Math.Round(Value,2, MidpointRounding.AwayFromZero);
//but it returns the value 500.03 instead of 500.04
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您要求非标准舍入规则。值 500.03499999999 四舍五入到最接近的百分位应为 500.03。由于千分位小于5,所以百分位保持不变。
我认为实现您想要的结果的一种方法是将数字四舍五入到比您最终想要的小一位的小数位。然后将该结果舍入到您想要的精度。
在您的示例中,您将该值四舍五入到小数点后 3 位,结果为 500.035。然后,您可以将其四舍五入到小数点后两位,结果应为 500.04(假设您使用的是
MidpointRounding.AwayFromZero
)。希望有所帮助。
You're asking for non-standard rounding rules. The value 500.03499999999 rounded to the nearest hundredth should be 500.03. Since the thousandths digit is less than 5, the hundredths digit remains unchanged.
One way I can see to achieve your desired result is to round the number to the decimal place one smaller than what you ultimately want. Then round that result to the precision you want.
In your example, you would round the value to 3 decimal places resulting in 500.035. You would then round that to 2 decimal places which should result in 500.04 (assuming you're using
MidpointRounding.AwayFromZero
.Hope that helps.
您可以使其变得不必要的复杂,并将变量 Round(Decimal, Int32) 函数包装在 for 循环中。递减 Int32 以使其返回到所需的十进制精度。这需要一些工作,但就像埃里克所说,您要求非标准舍入规则。
额外详细信息:http://msdn.microsoft.com/en-us/library/ ms131274.aspx
You could make it needlessly complex and wrap a variable Round(Decimal, Int32) function in a for loop. Decrement the Int32 to work it's way back to the decimal precision needed. It's a bit of work but like Eric said, you are asking for non-standard rounding rules.
Extra details: http://msdn.microsoft.com/en-us/library/ms131274.aspx