Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีใช้ String.Format แสดงทศนิยม 2 ตำแหน่ง หรือจำนวนเต็มใน C#

String.Format และ String Interpolation ($"") ใช้ Composite Formatting กับ Standard Numeric Format Strings เพื่อควบคุมการแสดงผลตัวเลข

Format Specifiers สำคัญ

Format ชื่อ ตัวอย่าง (123.456) ตัวอย่าง (123)
F2 / 0.00 Fixed-point (2 Decimal) 123.46 123.00
N2 Number with Group Separator 123.46 123.00
G / G29 General (Default) 123.456 123
#.## Custom: Optional Decimals 123.46 123
0.## Custom: Min 1 Digit, Max 2 Decimals 123.46 123

ตัวอย่าง: String.Format

int number = 123;
decimal price = 123.456m;

// Fixed 2 Decimals (Always show .00)
string s1 = string.Format("{0:F2}", number);     // "123.00"
string s2 = string.Format("{0:F2}", price);      // "123.46"

// Number with Comma Separator
string s3 = string.Format("{0:N2}", 1234567.89); // "1,234,567.89"

// Custom: Show Decimals Only If Needed
string s4 = string.Format("{0:0.##}", 123.456);  // "123.46"
string s5 = string.Format("{0:0.##}", 123);      // "123"
string s6 = string.Format("{0:0.##}", 123.4);    // "123.4"

// Multiple Values
string combined = string.Format("Price: {0:C2}, Qty: {1:N0}, Total: {2:C2}", 
    19.99, 100, 1999.00);
// "Price: $19.99, Qty: 100, Total: $1,999.00"

ตัวอย่าง: String Interpolation (C# 6+ - แนะนำ)

int number = 123;
decimal price = 123.456m;

// Basic
string s1 = $"{number:F2}";        // "123.00"
string s2 = $"{price:F2}";         // "123.46"

// Conditional Decimals (Custom Format)
string s3 = $"{price:0.##}";       // "123.46"
string s4 = $"{123m:0.##}";        // "123"
string s5 = $"{123.4m:0.##}";      // "123.4"

// With Culture (Important for Decimal Separator)
var thai = new CultureInfo("th-TH");
string s6 = $"{price.ToString("N2", thai)}"; // "123.46" (Thai uses .)

// Inline Expression
string msg = $"Total: {quantity * unitPrice:C2}";

การจัดการ "Integer แสดง Integer, Decimal แสดง 2 ตำแหน่ง"

public static string FormatNumber(dynamic value)
{
    // ตรวจสอบว่าเป็น Integer Type หรือมีทศนิยมเป็น 0
    if (value is int || value is long || value is short || value is byte)
        return value.ToString(); // "123"
    
    if (value is decimal d && d == Math.Truncate(d))
        return d.ToString("F0"); // "123"
    
    if (value is double dbl && dbl == Math.Truncate(dbl))
        return dbl.ToString("F0");
    
    // Default: 2 Decimals
    return Convert.ToDecimal(value).ToString("F2");
}

// หรือใช้ Custom Formatter
public static string SmartFormat(decimal value)
{
    return value % 1 == 0 ? value.ToString("F0") : value.ToString("F2");
}

// ใช้งาน
Console.WriteLine(SmartFormat(123m));      // "123"
Console.WriteLine(SmartFormat(123.00m));   // "123"
Console.WriteLine(SmartFormat(123.45m));   // "123.45"
Console.WriteLine(SmartFormat(123.456m));  // "123.46" (Rounded)

IFormattable และ ICustomFormatter (Advanced)

// Custom Format Provider สำหรับ "Smart" Format
public class SmartNumberFormatProvider : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType) => formatType == typeof(ICustomFormatter) ? this : null;
    
    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (arg is decimal d)
        {
            return d % 1 == 0 ? d.ToString("F0") : d.ToString("F2");
        }
        if (arg is double dbl)
        {
            return dbl % 1 == 0 ? dbl.ToString("F0") : dbl.ToString("F2");
        }
        return arg?.ToString() ?? "";
    }
}

// ใช้งาน
var provider = new SmartNumberFormatProvider();
string result = string.Format(provider, "{0} - {1}", 123m, 123.45m); // "123 - 123.45"

สรุป

  • F2 / 0.00: แสดง 2 ตำแหน่งเสมอ (Padding Zero)
  • 0.## / #.##: แสดงทศนิยมได้สูงสุด 2 ตำแหน่ง (Trim Trailing Zeros)
  • String Interpolation $"" อ่านง่ายกว่า String.Format
  • ใช้ CultureInfo สำหรับ Localization (Decimal Separator, Currency Symbol)
  • สำหรับ Logic "Integer แสดง Integer, Decimal แสดง Decimals" ให้เขียน Helper Method