How to Format Numbers as Currency in C#
When working with financial data in C#, proper currency formatting is essential for clear and professional presentation. The .NET framework provides several convenient methods to format numeric values as currency, with the most common being the ToString() method with the "C" format specifier.
For example, decimal amount = 1234.56m; string formatted = amount.ToString("C");
will display "$1,234.56" in US culture.
For more control over the formatting, you can specify a culture explicitly using CultureInfo - amount.ToString("C", new CultureInfo("fr-FR"))
would display "1 234,56 €".
This allows your application to handle different currency symbols, decimal separators, and grouping conventions appropriately.
If you need to handle multiple currencies or require more specialized formatting, you can also use the String.Format() method or string interpolation with custom format strings.
For instance, String.Format("{0:C}", amount)
or $"{amount:C}"
achieves the same result as ToString("C"). Additionally, you can control the number of decimal places using format strings like "C2" for two decimal places.
Remember that when dealing with financial calculations, it's best practice to use the decimal type rather than float or double to avoid rounding errors that could impact currency calculations.
Example
decimal price = 1234.56m;
// Basic currency formatting
Console.WriteLine(price.ToString("C")); // Output: $1,234.56
// Currency formatting with specific culture
Console.WriteLine(price.ToString("C", new CultureInfo("de-DE"))); // Output: 1.234,56 €
// Currency formatting with string interpolation
Console.WriteLine($"{price:C}"); // Output: $1,234.56
// Controlling decimal places
Console.WriteLine(price.ToString("C3")); // Output: $1,234.560