Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Format số thập phân 2 chữ số hoặc nguyên với String.Format trong C#

string.Format và String Interpolation ($"") sử dụng Composite Formatting với format specifier.

Format Specifier cho số

SpecifierMô tảVí dụ (123.456)Ví dụ (123)
N / N2Number với group separator, decimal places123.46123.00
F / F2Fixed-point (luôn có phần thập phân)123.46123.00
0.00Custom: ít nhất 1 chữ số nguyên, 2 chữ số thập phân123.46123.00
0.##Custom: tối đa 2 chữ số thập phân, bỏ .00 nếu nguyên123.46123
#.##Custom: bỏ leading zero, tối đa 2 dp123.46123
G / G29General (mặc định)123.456123

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 / F2 cho tiền tệ, báo cáo (luôn 2 chữ số).
  • Luôn chỉ định CultureInfo (thường InvariantCulture) cho log, file, API để nhất quán.