Math.Round默认采用的不是四舍五入法, 而是四舍六入的银行家算法, 也就是四舍六入五考虑,五后非零就进一,五后皆零看奇偶,五前为偶应舍 去,五前为奇要进一, 这个算法比四舍五入更精确些.
Response.Write("<BR>" + Math.Round(144.34, 1)); --144.3
Response.Write("<BR>" + Math.Round(144.15, 1)); --144.2
Response.Write("<BR>" + Math.Round(144.25, 1)); --144.2
Response.Write("<BR>" + Math.Round(144.35, 1)); --144.4
Response.Write("<BR>" + Math.Round(144.36, 1)); --144.4
但这根我们有些场合的预期结果有差异, 不太一致? 如何找回熟悉的四舍五入法? 加上MidpointRounding.AwayFromZero参数即可.
Response.Write("<BR>" + Math.Round(144.34, 1, MidpointRounding.AwayFromZero));
Response.Write("<BR>" + Math.Round(144.15, 1, MidpointRounding.AwayFromZero));
Response.Write("<BR>" + Math.Round(144.25, 1, MidpointRounding.AwayFromZero));
Response.Write("<BR>" + Math.Round(144.35, 1, MidpointRounding.AwayFromZero));
Response.Write("<BR>" + Math.Round(144.36, 1, MidpointRounding.AwayFromZero));
如果加MidpointRounding.ToEven, 则又返回了四舍六入.