0
0
C Sharp (C#)programming~5 mins

Format specifiers for numbers and dates in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Format specifiers help you show numbers and dates in a way that is easy to read and understand.

When you want to show a price with two decimal places, like $12.50.
When you want to display a date in a friendly format, like 01/31/2024.
When you want to add commas to large numbers, like 1,000,000.
When you want to show time in hours and minutes, like 14:30.
When you want to format percentages, like 75%.
Syntax
C Sharp (C#)
string formatted = value.ToString("formatSpecifier");

The formatSpecifier is a code inside quotes that tells how to show the number or date.

You use ToString() method on numbers or dates to format them.

Examples
Formats the number as currency with 2 decimal places, e.g., "$12.50".
C Sharp (C#)
double price = 12.5;
string formattedPrice = price.ToString("C2");
Formats the number with commas and no decimals, e.g., "1,000,000".
C Sharp (C#)
int number = 1000000;
string formattedNumber = number.ToString("N0");
Formats the date as month/day/year, e.g., "01/31/2024".
C Sharp (C#)
DateTime date = new DateTime(2024, 1, 31);
string formattedDate = date.ToString("MM/dd/yyyy");
Formats the number as a percentage with no decimals, e.g., "75%".
C Sharp (C#)
double percent = 0.75;
string formattedPercent = percent.ToString("P0");
Sample Program

This program shows how to format a price as currency, a large number with commas, a date in a full readable format, and a ratio as a percentage with one decimal place.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        double price = 1234.567;
        int largeNumber = 1000000;
        DateTime today = new DateTime(2024, 6, 15);
        double ratio = 0.8567;

        string priceFormatted = price.ToString("C2");
        string numberFormatted = largeNumber.ToString("N0");
        string dateFormatted = today.ToString("dddd, MMMM dd, yyyy");
        string percentFormatted = ratio.ToString("P1");

        Console.WriteLine(priceFormatted);
        Console.WriteLine(numberFormatted);
        Console.WriteLine(dateFormatted);
        Console.WriteLine(percentFormatted);
    }
}
OutputSuccess
Important Notes

Format specifiers are case-insensitive, so "C" and "c" both mean currency. Always check the documentation.

For dates, you can combine letters like "yyyy" for year, "MM" for month, and "dd" for day.

Use CultureInfo if you want to format numbers or dates for different countries.

Summary

Format specifiers help show numbers and dates clearly.

Use ToString("format") to apply formatting.

Common formats include currency, number with commas, dates, and percentages.