苏飞论坛

标题: C# Math.Round()方法详解 [打印本页]

作者: 站长苏飞    时间: 2014-4-29 09:25
标题: C# Math.Round()方法详解
C# Math.Round()方法详解


不能直接调用Math.Round方法的,这可和Java的不一样哦

Math.Round这个函数的解释是将值按指定的小数位数舍入,并不就是四舍五入。这种舍入有时称为就近舍入或四舍六入五成双

[C#] 纯文本查看 复制代码
Math.Round(0.4) //result:0
Math.Round(0.6) //result:1
Math.Round(0.5) //result:0
Math.Round(1.5) //result:2
Math.Round(2.5) //result:2
Math.Round(3.5) //result:4
Math.Round(5.5) //result:6
Math.Round(6.5) //result:6
Math.Round(8.5) //result:8
Math.Round(9.5) //result:10


可以看出 并不是四舍五入的   
其实在 VB, VBScript, C#, J#, T-SQL 中 Round 函数都是采用 Banker's rounding(银行家舍入)算法,即四舍六入五取偶。事实上这也是 IEEE 规定的舍入标准。因此所有符合 IEEE 标准的语言都应该是采用这一算法的。

请调用 Math.Round(Decimal, MidpointRounding) 重载!~哦,原来还有重载的方法可用,MidpointRounding在两个数字之间时如何舍入的规范,规范MidpointRounding中它有2个成员,一个是ToEven还有个是AwayFromZero。

[C#] 纯文本查看 复制代码

//四舍五入
Math.Round(0.5,MidpointRounding.AwayFromZero)

作者: 站长苏飞    时间: 2014-4-29 09:26
Math.Round(0.4,2);
其实第二个参数2表示返回的小数位数
作者: azon    时间: 2014-4-29 18:44
受教了。谢谢




欢迎光临 苏飞论坛 (http://www.sufeinet.com/) Powered by Discuz! X3.4