close

 

今天在算金額的時候使用到 Math.Round(),

Math.Round(24.5) 結果等於 24。

 

還好及時發現金額出錯,不然之後金額算錯就麻煩了!

那為甚麼24.5 四捨五入之後 卻會出現 24呢?

 

根據官網:

https://docs.microsoft.com/zh-tw/dotnet/api/system.math.round?view=net-5.0#Round4_Example

 

Math.Round()會有幾種用法,請一定要看 第3種 和 第4種 的比較

1.Math.Round(24.5)

結果為 :24

 

2.Math.Round(24.5, MidpointRounding.ToEven)

24.5要接近偶數的那一個數字。

結果為 :24

 

3.Math.Round(24.5, 0,MidpointRounding.AwayFromZero))

24.5四捨五入到小數點第0位數。 所以是0的時候就是 24.5 四捨五入到整數位數,會變成25

結果為 :25

 

4.Math.Round(24.55, 1,MidpointRounding.AwayFromZero))

 24.55 四捨五入到小數點第1位數。 所以是1的時候就是 24.55 四捨五入會變成24.6

結果為 :25

              

所以在預設下,就會是 Math.Round(value) 的情況。

 

結論:

正常四捨五入做法,

Math.Round(value, MidpointRounding.AwayFromZero)

 

arrow
arrow

    阿駿 發表在 痞客邦 留言(0) 人氣()