Number Formatting

C# Number Formatting

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

  1. 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.

  • P (Percent): Formats the number as a percentage.

using System;

class Program
{
    static void Main()
    {
        double value = 1234.5678;

        Console.WriteLine(value.ToString("C"));  // Currency
        Console.WriteLine(value.ToString("D"));  // Decimal
        Console.WriteLine(value.ToString("E"));  // Exponential
        Console.WriteLine(value.ToString("F"));  // Fixed-point
        Console.WriteLine(value.ToString("N"));  // Number
        Console.WriteLine(value.ToString("P"));  // Percent
    }
}

Advanced Features

  1. Custom Numeric Format Strings

You can create custom formats to fit specific needs using special format specifiers.

  1. 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.