[C#] Format Numbers as String
Examples
Some examples and tips on C# number formatting using string.Format() or
.ToString() methods.
Decimal point and Thousand separator
Use "." (point) for set the position of the decimal separetor and "," (comma)
for thousand separator.
double number = 1234.56;
string.Format("{0:0.000}", number) // 1234.560
string.Format("{0:#,0.00}", number) // 1,234.56
string.Format("{0:#,0.####}", number) // 1,234.56
// Thousand separator and number scaling
string.Format("{0:#,0}", 123000000) // 123,000,000
string.Format("{0:#,0, K}", 123000000) // 123,000 K
string.Format("{0:#,0,, M}", 123000000) // 123 M
Positive, nevative and zero format
It's possible provide different format for positivie, negative and zero-value
number by separating differet format with ";" character.
1 of 3
double number = 1234.56;
double numberNeg = -1234.56;
double numberZero = 0;
string.Format("{0:0.00}", number) // 1234.56
string.Format("{0:0.00}", numberNeg) // -1234.56
string.Format("{0:0.00}", numberZero) // 0.00
string.Format("{0:0.00;(0.00);0}", number) // 1234.56
string.Format("{0:0.00;(0.00);0}", numberNeg) // (1234.56)
string.Format("{0:0.00;(0.00);0}", numberZero) // 0
string.Format("{0:0.00;'neg: '-0.00;zero}", numberNeg) // neg: -1234.56
string.Format("{0:0.00;'neg: '-0.00;zero}", numberZero) // zero
Character escape and text
Any characters not used by the formatter is reported in the result string. If
you need to enter text with reserved characters that must be inserted
between two ' (single quote).
double numberNeg = -1234.56;
// unescaped text
string.Format("{0:0.00 Number}", number) // 1234.56 Number
string.Format("{0:0.00 #Num.}", number) // 1234.56 Num
// escaped text
string.Format("{0:0.00 '#Num.'}", number) // 1234.56 #Num.
TOOL: Test you format string
A simple tool for test your format string.
string.Format(" {0:0.00} ", 1234.56 ) Test
2 of 3
© 2020 - code-sample.net
3 of 3