Search code examples
c#formatnumber-formattingformat-string

Formatting numbers in a table view


I am formatting the numbers displayed in my table view. The numbers are formatted correctly - i.e. 21000 displays as 21,000.

However, if the number in the table is 0, the number displayed is 00.

Column.FormatString = "{0:0,0}";

Above is the code I am using for this.


Solution

  • Checking the docs on Custom Numeric Format Strings, 0 means that a non-significant 0 should always be displayed, even if there is no corresponding digit. For example:

    • String.Format("{0:0.0}",0.6) will display 0.6 while
    • String.Format("{0:#.0}",0.6) will display .6

    The same holds for the thousand separator although the result is rather... unexpected. Since there's no thousand separator, a 0 is displayd but , is not :

    • String.Format("{0:0,0}",0) will display 00 while
    • String.Format("{0:#,0}",0) will display 0

    String.Format allows separate formats for positive, negative and zeros. If you want to retain the leading 0 but display only a single 0 for zero, you can use

    String.Format("{0:0,0;-0,0;0}",0);