In this article, we will learn how to use the String.Format function to format a string into Decimal number format.

How to format a Double in C# using String.Format

For example, if you have to format a number up to two decimal places, use a pattern that specifies two zeros after point such as 0.00. If a number has fewer decimal places, the rest of the digits are on the right side will be replaced by zeros. If it has more decimal places, the number will be rounded.

    Console.Write(String.Format("{0:0.00}", 123.456789));
    Console.Write(String.Format("{0:0.00}", 12345.6));
    Console.Write(String.Format("{0:0.00}", 123456));



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));



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



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));



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);


minus 123.45

Related Articles

Last modified: September 17, 2019


Write a Reply or Comment

Your email address will not be published.