C# provides a variety of ways to format numbers to make them more readable and to present them in specific formats. This is particularly useful for displaying data to users in a human-readable form, handling currency, percentages, and custom formats.
Key Concepts
Standard Numeric Format Strings
C# offers predefined formats for common scenarios like currency, decimal, and percentages.
Examples
Using Standard Numeric Format Strings
C (Currency): Formats the number as a currency value.
D (Decimal): Formats the number as a decimal.
E (Exponential): Formats the number in scientific notation.
F (Fixed-point): Formats the number as a fixed-point number.
N (Number): Formats the number with thousand separators.
You can create custom formats to fit specific needs using special format specifiers.
Culture-Specific Formatting
Numeric formatting can be affected by culture settings, which control aspects like currency symbols, decimal separators, and digit grouping.
Summary
Standard Numeric Format Strings: Common formats like currency, decimal, percentage.
Custom Numeric Format Strings: Allows for specific, tailored number formatting.
Culture-Specific Formatting: Adapts number formatting to different cultural settings.
C# number formatting provides powerful tools to present numerical data in a clear and user-friendly way, enhancing the readability and usability of applications.
using System;
class Program
{
static void Main()
{
double value = 1234.5678;
// Custom formatting with "0" as a digit placeholder and "#" as an optional digit
Console.WriteLine(value.ToString("0.00")); // 1234.57
Console.WriteLine(value.ToString("00000")); // 01235
Console.WriteLine(value.ToString("#.##")); // 1234.57
Console.WriteLine(value.ToString("0,0.00")); // 1,234.57
Console.WriteLine(value.ToString("$#,##0.00")); // $1,234.57
}
}
using System;
using System.Globalization;
class Program
{
static void Main()
{
double value = 1234.5678;
CultureInfo usCulture = new CultureInfo("en-US");
CultureInfo frCulture = new CultureInfo("fr-FR");
Console.WriteLine(value.ToString("C", usCulture)); // $1,234.57
Console.WriteLine(value.ToString("C", frCulture)); // 1 234,57 €
}
}