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

前端 未结 15 2120
灰色年华
灰色年华 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:19

    Since Silverlight doesn't support the MidpointRounding option you have to write your own. Something like:

    public double RoundCorrect(double d, int decimals)
    {
        double multiplier = Math.Pow(10, decimals);
    
        if (d < 0)
            multiplier *= -1;
    
        return Math.Floor((d * multiplier) + 0.5) / multiplier;
    
    }
    

    For the examples including how to use this as an extension see the post: .NET and Silverlight Rounding

提交回复
热议问题