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

Định dạng chuỗi cho Double (String format) trong C#

Dùng phương thức tĩnh String.Format để định dạng double thành chuỗi.

Ba chữ số thập phân:

String.Format("{0:0.000}", 987.383);
String.Format("{0:0.000}", 987.38);
String.Format("{0:0.000}", 987.7899);

Phân cách hàng nghìn:

String.Format("{0:0,0.0}", 54567.46);
String.Format("{0:0,0}", 54567.46);

Ví dụ

using System;

class Demo {
    public static void Main(String[] args) {
        Console.WriteLine("Ba chữ số thập phân...");
        Console.WriteLine(String.Format("{0:0.000}", 987.383));
        Console.WriteLine(String.Format("{0:0.000}", 987.38));
        Console.WriteLine(String.Format("{0:0.000}", 987.7899));
        Console.WriteLine("Phân cách hàng nghìn...");
        Console.WriteLine(String.Format("{0:0,0.0}", 54567.46));
        Console.WriteLine(String.Format("{0:0,0}", 54567.46));
    }
}