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

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

I want to do this using the Math.Round function

15条回答
  •  Happy的楠姐
    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
    

提交回复
热议问题