string.Format và String Interpolation ($"") sử dụng Composite Formatting với format specifier.
Format Specifier cho số
| Specifier | Mô tả | Ví dụ (123.456) | Ví dụ (123) |
|---|---|---|---|
N / N2 | Number với group separator, decimal places | 123.46 | 123.00 |
F / F2 | Fixed-point (luôn có phần thập phân) | 123.46 | 123.00 |
0.00 | Custom: ít nhất 1 chữ số nguyên, 2 chữ số thập phân | 123.46 | 123.00 |
0.## | Custom: tối đa 2 chữ số thập phân, bỏ .00 nếu nguyên | 123.46 | 123 |
#.## | Custom: bỏ leading zero, tối đa 2 dp | 123.46 | 123 |
G / G29 | General (mặc định) | 123.456 | 123 |
Ví dụ: String.Format
decimal price1 = 123.456m;
decimal price2 = 123m;
Console.WriteLine(string.Format("Price: {0:N2}", price1)); // Price: 123.46
Console.WriteLine(string.Format("Price: {0:N2}", price2)); // Price: 123.00
Console.WriteLine(string.Format("Price: {0:0.00}", price1)); // Price: 123.46
Console.WriteLine(string.Format("Price: {0:0.00}", price2)); // Price: 123.00
Console.WriteLine(string.Format("Price: {0:0.##}", price1)); // Price: 123.46
Console.WriteLine(string.Format("Price: {0:0.##}", price2)); // Price: 123
Ví dụ: String Interpolation (C# 6+, khuyến nghị)
decimal price = 123.456m;
int quantity = 10;
// Cơ bản
Console.WriteLine($"Price: {price:N2}"); // Price: 123.46
Console.WriteLine($"Price: {price:0.##}"); // Price: 123.46
Console.WriteLine($"Total: {price * quantity:C}"); // Total: $1,234.56 (currency)
// Conditional format
string FormatPrice(decimal p) => p == Math.Truncate(p)
? $"{p:0}" // Nguyên: 123
: $"{p:0.##}"; // Thập phân: 123.46
Console.WriteLine(FormatPrice(123)); // 123
Console.WriteLine(FormatPrice(123.4)); // 123.4
Console.WriteLine(FormatPrice(123.456)); // 123.46
Format Provider (Culture)
using System.Globalization;
var vi = new CultureInfo("vi-VN");
var us = CultureInfo.InvariantCulture;
decimal d = 1234.56m;
Console.WriteLine(d.ToString("N2", vi)); // 1.234,56 (dấu phẩy thập phân VN)
Console.WriteLine(d.ToString("N2", us)); // 1,234.56 (dấu chấm US)
Console.WriteLine($"{d.ToString("N2", vi)}"); // Interpolation cũng dùng được
Best Practice
- Dùng String Interpolation ($"") cho readability và performance.
- Dùng
0.##nếu muốn hiển thị nguyên gọn, thập phân tối đa 2 chữ số. - Dùng
N2/F2cho tiền tệ, báo cáo (luôn 2 chữ số). - Luôn chỉ định
CultureInfo(thườngInvariantCulture) cho log, file, API để nhất quán.