How do you round a number to two decimal places in C#?

后端 未结 15 1029
挽巷
挽巷 2020-11-22 08:59

I want to do this using the Math.Round function

相关标签:
15条回答
  • 2020-11-22 09:48

    Had a weird situation where I had a decimal variable, when serializing 55.50 it always sets default value mathematically as 55.5. But whereas, our client system is seriously expecting 55.50 for some reason and they definitely expected decimal. Thats when I had write the below helper, which always converts any decimal value padded to 2 digits with zeros instead of sending a string.

    public static class DecimalExtensions
    {
        public static decimal WithTwoDecimalPoints(this decimal val)
        {
            return decimal.Parse(val.ToString("0.00"));
        }
    }
    

    Usage should be

    var sampleDecimalValueV1 = 2.5m;
    Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());
    
    decimal sampleDecimalValueV1 = 2;
    Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());
    

    Output:

    2.50
    2.00
    
    0 讨论(0)
  • 2020-11-22 09:53

    Personally I never round anything. Keep it as resolute as possible, since rounding is a bit of a red herring in CS anyway. But you do want to format data for your users, and to that end, I find that string.Format("{0:0.00}", number) is a good approach.

    0 讨论(0)
  • 2020-11-22 10:00

    Here's some examples:

    decimal a = 1.994444M;
    
    Math.Round(a, 2); //returns 1.99
    
    decimal b = 1.995555M;
    
    Math.Round(b, 2); //returns 2.00
    

    You might also want to look at bankers rounding / round-to-even with the following overload:

    Math.Round(a, 2, MidpointRounding.ToEven);
    

    There's more information on it here.

    0 讨论(0)
提交回复
热议问题