我最难理解为什么.NET中的Math.Round
函数(使用框架4.5)以某种方式运行:
Math.Round(21.4451m, 2, MidpointRounding.ToEven) // 21.45
当我将相同的最后一个小数位置设置为0而不是:
Math.Round(21.4450m, 2, MidpointRounding.ToEven) // 21.44
有人可以向我解释为什么当最后一个小数位为1或更多时,第一个例子的舍入结果是21.45?
我需要知道,因为我试图在SQL Server中编写一个与.NET框架完全匹配的算法(因为SQL Server使用算术舍入)。
答案 0 :(得分:4)
您正在四舍五入到小数点后两位。您正在使用ToEven:
如果一个数字介于另外两个数字之间,那么它将向四舍五入 最近的偶数。
任何数字大于 21.445(> 21.445)将转为21.45
任何小于或等于 21.445(< = 21.445)的数字将会转为21.44。
Math.Round(21.44500001m, 2, MidpointRounding.ToEven); //>21.445 therefore 21.45
Math.Round(21.44500000m, 2, MidpointRounding.ToEven); //=21.445 therefore 21.44
Math.Round(21.44499999m, 2, MidpointRounding.ToEven); //<21.445 therefore 21.44
它正常工作。 ;)
为了获得与SQL中相同的ROUND行为,请使用AwayFromZero。
SELECT ROUND(21.4451, 2), ROUND(21.4450, 2), ROUND(21.4449, 2)
--less decimal casting, yields:
-- 21.4500 21.4500 21.4400
Math.Round(21.44500001m, 2, MidpointRounding.AwayFromZero); //21.45
Math.Round(21.44500000m, 2, MidpointRounding.AwayFromZero); //21.45
Math.Round(21.44499999m, 2, MidpointRounding.AwayFromZero); //21.44