Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
String Formatting with ToString in C#
The ToString() method in C# is a powerful way to format values into strings using various format specifiers. It provides control over how numbers, dates, and other data types are displayed as text.
Syntax
Following is the basic syntax for using ToString() with format specifiers −
variable.ToString("formatSpecifier");
For numeric formatting with custom patterns −
number.ToString("000"); // Zero padding
number.ToString("C"); // Currency format
number.ToString("F2"); // Fixed-point with 2 decimals
Using Zero Padding Format
The zero padding format ensures a number is displayed with a minimum number of digits, adding leading zeros if necessary −
using System;
public class Program {
public static void Main() {
int value = 55;
string res = value.ToString("000");
Console.WriteLine("Formatted value: " + res);
int smallValue = 7;
Console.WriteLine("Small value: " + smallValue.ToString("0000"));
}
}
The output of the above code is −
Formatted value: 055 Small value: 0007
Using Standard Numeric Format Specifiers
using System;
public class Program {
public static void Main() {
double value = 1234.567;
Console.WriteLine("Currency: " + value.ToString("C"));
Console.WriteLine("Fixed-point 2 decimals: " + value.ToString("F2"));
Console.WriteLine("Percentage: " + (0.85).ToString("P"));
Console.WriteLine("Scientific: " + value.ToString("E"));
}
}
The output of the above code is −
Currency: $1,234.57 Fixed-point 2 decimals: 1234.57 Percentage: 85.00% Scientific: 1.234567E+003
Using DateTime Formatting
using System;
public class Program {
public static void Main() {
DateTime now = DateTime.Now;
Console.WriteLine("Short date: " + now.ToString("d"));
Console.WriteLine("Long date: " + now.ToString("D"));
Console.WriteLine("Custom format: " + now.ToString("yyyy-MM-dd HH:mm:ss"));
Console.WriteLine("Month/Year: " + now.ToString("MMMM yyyy"));
}
}
The output of the above code is −
Short date: 12/15/2023 Long date: Friday, December 15, 2023 Custom format: 2023-12-15 14:30:45 Month/Year: December 2023
Common Format Specifiers
| Format | Description | Example |
|---|---|---|
| 000 | Zero padding | 55 ? "055" |
| C | Currency | 123.45 ? "$123.45" |
| F2 | Fixed-point, 2 decimals | 123.456 ? "123.46" |
| P | Percentage | 0.75 ? "75.00%" |
| E | Scientific notation | 1234 ? "1.234000E+003" |
Conclusion
The ToString() method with format specifiers provides flexible string formatting for numbers, dates, and other data types. It offers both standard formats like currency and percentage, as well as custom patterns for specific formatting needs.
