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

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

I want to do this using the Math.Round function

15条回答
  •  傲寒
    傲寒 (楼主)
    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.

提交回复
热议问题