Format specifiers help you show numbers and dates in a way that is easy to read and understand.
Format specifiers for numbers and dates in 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.
double price = 12.5; string formattedPrice = price.ToString("C2");
int number = 1000000; string formattedNumber = number.ToString("N0");
DateTime date = new DateTime(2024, 1, 31); string formattedDate = date.ToString("MM/dd/yyyy");
double percent = 0.75; string formattedPercent = percent.ToString("P0");
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.
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); } }
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.
Format specifiers help show numbers and dates clearly.
Use ToString("format") to apply formatting.
Common formats include currency, number with commas, dates, and percentages.