Standard Numeric Format Strings in C#
Description
We can use standard numeric format string to format a numeric value in one of two ways.
We can use it in ToString method with a format parameter. The following example formats a numeric value as a currency string in the current (in this case, the en-US) culture.
Example
decimal value = 123.456m;
Console.WriteLine(value.ToString("C2"));
The code above generates the following result.
We can also use the formatString parameter methods such as
String.Format
,
Console.WriteLine
, and
StringBuilder.AppendFormat
.
The following example uses a format item to insert a currency value in a string.
decimal value = 123.456m;
Console.WriteLine("Your account balance is {0:C2}.", value);
The code above generates the following result.