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

前端 未结 15 1769
灰色年华
灰色年华 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 04:21

    I had this problem where my SQL server rounds up 0.5 to 1 while my C# application didn't. So you would see two different results.

    Here's an implementation with int/long. This is how Java rounds.

    int roundedNumber = (int)Math.Floor(d + 0.5);
    

    It's probably the most efficient method you could think of as well.

    If you want to keep it a double and use decimal precision , then it's really just a matter of using exponents of 10 based on how many decimal places.

    public double getRounding(double number, int decimalPoints)
    {
        double decimalPowerOfTen = Math.Pow(10, decimalPoints);
        return Math.Floor(number * decimalPowerOfTen + 0.5)/ decimalPowerOfTen;
    }
    

    You can input a negative decimal for decimal points and it's word fine as well.

    getRounding(239, -2) = 200
    

提交回复
热议问题