C#中Math.Round()實現四捨五入

今天代碼需求想讓4.499999升上去獲取到5,但是Math.Round()會直接攝取取值4。記錄一下實現方法。

ps:第一個參數一定要強制轉換成decimal類型。

C#中的Math.Round()並不是使用的"四捨五入"法。其實在VB、VBScript、C#、J#、T-SQL中Round函數都是採用Banker's rounding(銀行家算法),即:四捨六入五取偶。事實上這也是IEEE的規範,因此所有符合IEEE標準的語言都應該採用這樣的算法。

.NET 2.0 開始,Math.Round 方法提供了一個枚舉選項 MidpointRounding.AwayFromZero 可以用來實現傳統意義上的"四捨五入"。即: Math.Round(4.5, MidpointRounding.AwayFromZero) = 5。

Round(Decimal)
Round(Double)
Round(Decimal, Int32)
Round(Decimal, MidpointRounding)
Round(Double, Int32)
Round(Double, MidpointRounding)
Round(Decimal, Int32, MidpointRounding)
Round(Double, Int32, MidpointRounding)

 如:

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(4.5) //result:4

Math.Round(5.5) //result:6

Math.Round(6.5) //result:6

Math.Round(7.5) //result:8

Math.Round(8.5) //result:8

Math.Round(9.5) //result:10

   使用MidpointRounding.AwayFromZero重載後對比:   

Math.Round(0.4, MidpointRounding.AwayFromZero); // result:0

Math.Round(0.6, MidpointRounding.AwayFromZero); // result:1

Math.Round(0.5, MidpointRounding.AwayFromZero); // result:1

Math.Round(1.5, MidpointRounding.AwayFromZero); // result:2

Math.Round(2.5, MidpointRounding.AwayFromZero); // result:3

Math.Round(3.5, MidpointRounding.AwayFromZero); // result:4

Math.Round(4.5, MidpointRounding.AwayFromZero); // result:5

Math.Round(5.5, MidpointRounding.AwayFromZero); // result:6

Math.Round(6.5, MidpointRounding.AwayFromZero); // result:7

Math.Round(7.5, MidpointRounding.AwayFromZero); // result:8

Math.Round(8.5, MidpointRounding.AwayFromZero); // result:9

Math.Round(9.5, MidpointRounding.AwayFromZero); // result:10

 

但是悲劇的是,如果用這個計算小數的話,就不靈了!!!

必須用第七個重載方法,
decimal Round(decimal d, int decimals, MidpointRounding mode)

這樣計算出來的小數纔是真正的中國式四捨五入!!

?Math.Round(526.925, 2)
526.92

?Math.Round(526.925, 2,MidpointRounding.AwayFromZero)
526.92

?Math.Round((decimal)526.925, 2)
526.92

?Math.Round((decimal)526.925, 2,MidpointRounding.AwayFromZero)
526.93

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章