Format currency with string
The pattern we used above is called the custom format. In C#, we have a few types of custom formats which we can to format the numbers, Such as zero placeholder – {0:00.00}, or digit placeholder {0:(#).##}, or percentage {0:0%}
Add Digits before decimal point using String.Format
If you want a specific number of digits before the decimal point, use zeros N-times before the decimal point.
For example. the code below ensures that there will always be three digits before the decimal point.
- Console.Write(String.Format("{0:000.0}", 123.456));
- Console.Write(String.Format("{0:000.0}", 12.3456));
- Console.Write(String.Format("{0:000.0}", 1.23456));
- Console.Write(String.Format("{0:000.0}", -1.23456));
Output
123.5
012.3
001.2
-001.2
Removing leading zero using String.Format
To format a decimal number without a leading zero, simply use # before the decimal point in your custom format.
- Console.Write(String.Format("{0:00.00}", 0.12)); // with leading zero
- Console.Write(String.Format("{0:00.#}", 0.12)); // without leading zero
Output
0.12
.12
Adding thousands separator using String.Format
Use zero and comma separator if you need to format a number to the string while placing the thousands separator.
- Console.Write(String.Format("{0:0,0.0}", 10000.00));
Output
10,000.0
Adding parenthesizes to negative Decimal using String.Format
The semicolon operator is used to create a custom formatting which separates positive, negative numbers and zeros.
- String.Format("{0:0.00;minus 0.00;zero}", -123.45);
- String.Format("{0: #, ##0.00; (#,##0.00)} ", -123.45);
Output
minus 123.45
(123.45)