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

In số có dấu phẩy phân cách hàng nghìn trong C#

Thiết lập số dưới dạng chuỗi:

string num = "1000000.8765";

Tách phần nguyên và phần thập phân:

string withoutDecimals = num.Substring(0, num.IndexOf("."));
string withDecimals = num.Substring(num.IndexOf("."));

Định dạng phần nguyên với ToString("N0") hoặc ToString("#,##0"):

withoutDecimals = Convert.ToInt32(withoutDecimals).ToString("#,##0");

Ví dụ hoàn chỉnh

using System;

public class Program
{
    public static void Main()
    {
        string num = "1000000.8765";
        string withoutDecimals = num.Substring(0, num.IndexOf("."));
        string withDecimals = num.Substring(num.IndexOf("."));
        
        withoutDecimals = Convert.ToInt32(withoutDecimals).ToString("#,##0");
        Console.WriteLine(withoutDecimals + withDecimals);
    }
}

Kết quả

1,000,000.8765

Cách tốt hơn: Parse trực tiếp sang số rồi format: double d = 1000000.8765; Console.WriteLine(d.ToString("N4")); hoặc string.Format("{0:N4}", d). Format "N" tự động thêm dấu phẩy và số chữ số thập phân.