Why does Math.Round(2.5) return 2 instead of 3?

前端 未结 15 1782
灰色年华
灰色年华 2020-11-22 03:54

In C#, the result of Math.Round(2.5) is 2.

It is supposed to be 3, isn\'t it? Why is it 2 instead in C#?

15条回答
  •  礼貌的吻别
    2020-11-22 04:36

    Here's the way i had to work it around :

    Public Function Round(number As Double, dec As Integer) As Double
        Dim decimalPowerOfTen = Math.Pow(10, dec)
        If CInt(number * decimalPowerOfTen) = Math.Round(number * decimalPowerOfTen, 2) Then
            Return Math.Round(number, 2, MidpointRounding.AwayFromZero)
        Else
            Return CInt(number * decimalPowerOfTen + 0.5) / 100
        End If
    End Function
    

    Trying with 1.905 with 2 decimals will give 1.91 as expected but Math.Round(1.905,2,MidpointRounding.AwayFromZero) gives 1.90! Math.Round method is absolutely inconsistent and unusable for most of the basics problems programmers may encounter. I have to check if (int) 1.905 * decimalPowerOfTen = Math.Round(number * decimalPowerOfTen, 2) cause i don not want to round up what should be round down.

提交回复
热议问题