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

來源:互聯網
上載者:User

標籤:

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

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.