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

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

I want to do this using the Math.Round function

15条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 09:45

    // convert upto two decimal places

    String.Format("{0:0.00}", 140.6767554);        // "140.67"
    String.Format("{0:0.00}", 140.1);             // "140.10"
    String.Format("{0:0.00}", 140);              // "140.00"
    
    Double d = 140.6767554;
    Double dc = Math.Round((Double)d, 2);       //  140.67
    
    decimal d = 140.6767554M;
    decimal dc = Math.Round(d, 2);             //  140.67
    

    =========

    // just two decimal places
    String.Format("{0:0.##}", 123.4567);      // "123.46"
    String.Format("{0:0.##}", 123.4);         // "123.4"
    String.Format("{0:0.##}", 123.0);         // "123"
    

    can also combine "0" with "#".

    String.Format("{0:0.0#}", 123.4567)       // "123.46"
    String.Format("{0:0.0#}", 123.4)          // "123.4"
    String.Format("{0:0.0#}", 123.0)          // "123.0"
    

提交回复
热议问题