How to set width and precision by params in C#? RRS feed

  • 问题

  • I want to write a method with 2 params, which are used for setting the width and precision when output a line.

    For example,

    MethodName(int width,int precision){



    I want to set width=6 and precision =2,thus I can get 0.00 with 2 spaces in the front.

    What should i do?

    2014年3月15日 2:37


  • Hi weird93,

    Please check the following sample code, not sure if it is what you want.

    static void Main(string[] args)
                //The result is "  1.23", two spaces are in the front.
            static string FormatNumber(double d, int width, int precision)
                string result = string.Empty;
                result = d.ToString(string.Format("F{0}", precision));
                result = (result.Length < width) ? result.PadLeft(width, ' ') : result;
                return result;

    If you want more information about double or deceimal value format, please refer to the MSDN document:

    Standard Numeric Format Strings

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2014年3月17日 6:26