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

จัดรูปแบบตัวเลขด้วย Comma (1000 Separator) ใน C#

การแสดงตัวเลขด้วย Comma คั่นพัน (Thousands Separator) ใน C# ทำได้หลายวิธี ขึ้นอยู่กับรูปแบบ Input และ Output ที่ต้องการ

วิธีที่ 1: ToString("N") หรือ ToString("#,##0") - แนะนำมากที่สุด

using System;

public class Program
{
    public static void Main()
    {
        double num = 1000000.8765;

        // วิธีมาตรฐาน
        Console.WriteLine(num.ToString("N"));        // 1,000,000.88 (2 ทศนิยม)
        Console.WriteLine(num.ToString("N4"));       // 1,000,000.8765 (4 ทศนิยม)
        Console.WriteLine(num.ToString("#,##0.####")); // 1,000,000.8765 (สูงสุด 4 ทศนิยม)
        Console.WriteLine(num.ToString("#,##0.00"));  // 1,000,000.88 (บังคับ 2 ทศนิยม)
    }
}

วิธีที่ 2: String.Format / Interpolation

double num = 1000000.8765;

Console.WriteLine(String.Format("{0:N}", num));     // 1,000,000.88
Console.WriteLine($"{num:N}");                       // 1,000,000.88
Console.WriteLine($"{num:N4}");                      // 1,000,000.8765
Console.WriteLine($"{num:#,##0.####}");              // 1,000,000.8765

วิธีที่ 3: String Input (จากต้นฉบับ) - Manual Parsing

string numStr = "1000000.8765";

// แยกส่วนเต็มและทศนิยม
int dotIndex = numStr.IndexOf('.');
string intPart = dotIndex >= 0 ? numStr.Substring(0, dotIndex) : numStr;
string decPart = dotIndex >= 0 ? numStr.Substring(dotIndex) : "";

// จัดรูปส่วนเต็ม
if (long.TryParse(intPart, out long intVal))
{
    string formatted = intVal.ToString("#,##0");
    Console.WriteLine(formatted + decPart); // 1,000,000.8765
}

Custom Culture (Thai/US/DE)

using System.Globalization;

double num = 1234567.89;

Console.WriteLine(num.ToString("N", new CultureInfo("en-US"))); // 1,234,567.89
Console.WriteLine(num.ToString("N", new CultureInfo("de-DE"))); // 1.234.567,89
Console.WriteLine(num.ToString("N", new CultureInfo("th-TH"))); // 1,234,567.89 (ไทยใช้ Comma/Dot เหมือน US)

// Custom Format Provider
var custom = new NumberFormatInfo
{
    NumberGroupSeparator = " ",
    NumberDecimalSeparator = ","
};
Console.WriteLine(num.ToString("N", custom)); // 1 234 567,89

Integer Formatting

int i = 1000000;
Console.WriteLine(i.ToString("N0"));      // 1,000,000
Console.WriteLine(i.ToString("#,##0"));   // 1,000,000
Console.WriteLine($"{i:#,##0}");          // 1,000,000

Parsing กลับ (String with Comma → Number)

string formatted = "1,000,000.8765";
double parsed = double.Parse(formatted, NumberStyles.AllowThousands | NumberStyles.Float,
                            CultureInfo.InvariantCulture);

สรุปแนะนำ

สถานการณ์วิธีแนะนำ
Number Type (int, double, decimal)ToString("N") หรือ $"{num:N}"
String Input (มี Comma อยู่แล้ว)Parse ด้วย NumberStyles.AllowThousands
String Input (ไม่มี Comma)Parse → ToString("N")
Custom SeparatorNumberFormatInfo