Math.Round這個(gè)函數(shù)的解釋是將值按指定的小數(shù)位數(shù)舍入,并不就是四舍五入。這種舍入有時(shí)稱為就近舍入或四舍六入五成雙
C# code
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
可以看出 并不是四舍五入的
其實(shí)在 VB, VBScript, C#, J#, T-SQL 中 Round 函數(shù)都是采用 Banker's rounding(銀行家舍入)
算法,即四舍六入五取偶
。事實(shí)上這也是 IEEE 規(guī)定的舍入標(biāo)準(zhǔn)
。因此所有符合 IEEE 標(biāo)準(zhǔn)的語言都應(yīng)該是采用這一算法的。
請(qǐng)調(diào)用 Math.Round(Decimal, MidpointRounding) 重載!~哦,原來還有重載的方法可用,MidpointRounding在兩個(gè)數(shù)字之間時(shí)如何舍入的規(guī)范,規(guī)范MidpointRounding中它有2個(gè)成員,一個(gè)是ToEven還有個(gè)是AwayFromZero。
C# code
//四舍五入
Math.Round(0.5,MidpointRounding.AwayFromZero)
1. (int )double
2. convert.toInt32(object),object可能為string
3. int.parse(string)
Note:
Convert.ToInt32(null)會(huì)返回0而不會(huì)產(chǎn)生任何異常,但int.Parse(null)則 會(huì)產(chǎn)生異常。
Convert.ToInt32(double value),使用的上邊的銀行家舍入算法
。
(int )double,直接是強(qiáng)制轉(zhuǎn)換(即截取整數(shù)部分
)