.netformattingnumeric

Numerical formatting using String.Format


Are there any codes that allow for numerical formatting of data when using string.format?


Solution

  • Yes, you can specify the formatting after a : in the {} placeholder.

    specifier type format output (double 1234.56)
    0 zero placeholder {0:00.000} 1234.560
    # digit placeholder {0:#.##} 1234.56
    . decimal point placeholder {0:0.0} 1234.6
    , thousand separator {0:0,0} 1,235
    % percentage {0:0%} 123456%

    In addition there is the group separator ; this is useful for varying the format, depending on the value of the parameter passed. For example:

    string.Format("{0:£#,##0.00;(£#,##0.00);Nothing}", value);
    

    This will output "£1,240.00" if passed 1243.56. It will output the same format bracketed if the value is negative "(£1,240.00)", and will output the string "Nothing" if the number is zero.