一直以为Math.Round就是四舍五入,谁知道没加参数,得到的结果就是有问题
测试代码:
void Main()
{
string.Format("Round {0} = {1}",2.4M,Math.Round(2.4M,0)).Dump();
string.Format("Round {0} = {1}",2.5M,Math.Round(2.5M,0)).Dump();
string.Format("Round {0} = {1}",2.6M,Math.Round(2.6M,0)).Dump();
string.Format("Round {0} = {1}",3.4M,Math.Round(3.4M,0)).Dump();
string.Format("Round {0} = {1}",3.5M,Math.Round(3.5M,0)).Dump();
string.Format("Round {0} = {1}",3.6M,Math.Round(3.6M,0)).Dump();
}
输出内容:
Round 2.4 = 2
Round 2.5 = 2
Round 2.6 = 3
Round 3.4 = 3
Round 3.5 = 4
Round 3.6 = 4
官方文档:https://msdn.microsoft.com/zh-cn/library/system.midpointrounding(v=vs.110).aspx
其实,我们要做到四舍五入,只要调用重载函数,指定舍入的方式就行了,如:
string.Format("Round {0} = {1}",2.5M,Math.Round(2.5M,0, MidpointRounding.AwayFromZero)).Dump();
这个结果,就是3了。
时间: 2024-11-03 06:56:53