In this tutorial, we will learn how to format decimal or double numbers into string in C#. String.Format converts the value of objects into strings based on the given formats.
String.Format converts the value of objects into strings based on the given formats. Below examples shows how to format double or decimal values to string in C#.
To format the numbers to fixed decimal places, you can use the “0” custom specifier as shown in the below example:
1 2 3 4 5 6 7 8 | public static void Main (string[] args) { Console.WriteLine(string.Format("{0:0.00}", 1234.568)); Console.WriteLine(string.Format("{0:0.00}", 1234.562)); Console.WriteLine(string.Format("{0:0.00}", 1234.5)); Console.WriteLine(string.Format("{0:0.00}", 1234.0)); } |
To format the numbers to a maximum of two decimal places, you can use the “#” custom specifier as shown in the below example:
1 2 3 4 5 6 | string.Format("{0:0.##}", 1234.568) // 1234.57 string.Format("{0:0.##}", 1234.562) // 1234.56 string.Format("{0:0.##}", 1234.5) // 1234.5 string.Format("{0:0.##}", 1234.0) // 1234 |
To format the numbers to any minimum number of digits, you can use the “.” custom specifier as shown in the below example:
1 2 3 4 5 | string.Format("{0:0.0}", 1234.568) // 1234.6 string.Format("{0:0.0}", 1234.5) // 1234.5 string.Format("{0:0.0}", 1234.0) // 1234.0 |
To format the numbers with thousands separator, you can use the “,” custom specifier as shown in the below example:
1 2 3 4 5 | string.Format("{0:0,0.000}", 12345678.901) // 1,23,45,678.901 string.Format("{0:0,0.00}", 12345678.901) // 1,23,45,678.90 string.Format("{0:0,0}", 12345678.901) // 1,23,45,679 |
To format positive, negative numbers and zero, you can use “;” custom specifier to split the pattern into 3 sections as shown in the below example:
1 2 3 4 5 6 7 8 9 | string.Format("{0:0.00}", 123456.789) // 123456.79 string.Format("{0:0.00}", -123456.789) // -123456.79 // {0:[positive];[negative];[zero]} string.Format("{0:0.00;'negative: '-0.00;zero}", 123456.789) // 123456.79 string.Format("{0:0.00;'negative: '-0.00;zero}", -123456.789) // negative: -123456.79 string.Format("{0:0.00;'negative: '-0.00;zero}", 0.0) // Zero |
To align numbers with spaces then use “,” before the colon and align numbers to the left use a negative number of spaces.
1 2 3 4 5 6 7 8 | // Postitive values string.Format("{0,10:0.0}", 123456.789) //" 123456.8" string.Format("{0,10:0.0}", -123456.789) //" -123456.8" // Negative values string.Format("{0,-10:0.0}", 123456.789) //"123456.8 " string.Format("{0,-10:0.0}", -123456.789) //"-123456.8 " |