Use custom numeric formats in C#

custom numeric formats

You can use formatting characters to display custom numeric formats for numeric values. These formats work with a variable’s ToString method as well as with string.Format. For example, the code (1.234).ToString("0.00") returns the value “1.23.”

This example builds a ListView that describes the various custom numeric format characters. It then builds another ListView that shows examples. Finally the program uses code from the example Use ListView data to generate HTML TABLE code in C# to convert the results into the following HTML tables.

Name Format Result
Zero placeholder 0 A digit or 0 if no digit is present
Digit placeholder # A digit or nothing if no digit is present
Decimal separator . The decimal separator
Thousands separator , Thousands separator
Scaling , When placed at the end of the format string, divides by 1000
Percent placeholder % Multiplies by 100 and inserts a percent symbol
Per mille placeholder Multiplies by 100 and inserts a per mille symbol
Exponentiation E+0 Exponentiation.
Escape character \ The following character is not interpreted as a formatting character
Literal string ‘…’ The characters in single or double quotes are displayed literally
Section separator ; Creates up to three sections for values > 0, < 0, or = 0.
Example Result
123(“00000”) 00123
123(“#####”) 123
123.4567(“0.00”) 123.46
1234567890(“#,#”) 1,234,567,890
1234567890(“#,#,,”) 1,235
0.1234(“#.#%”) 12.3%
1234567890(“#E000”) 1E009
1234567890(“#E+000”) 1E+009
0.00001234(“#E000”) 1E-005
1.234(“+0.00;<0.00>;-zero-“) +1.23
-1.234(“+0.00;<0.00>;-zero-“) <1.23>
0(“+0.00;<0.00>;-zero-“) -zero-

Download Example   Follow me on Twitter   RSS feed

This entry was posted in formatting, strings and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *