Custom format specifier "#" hoạt động như ký tự giữ chỗ cho chữ số (digit-placeholder symbol).
Nếu giá trị được định dạng có chữ số ở vị trí nơi ký hiệu "#" xuất hiện trong chuỗi định dạng, thì chữ số đó được sao chép vào chuỗi kết quả.
Chúng ta có kiểu double ở đây.
double d; d = 4.2;
Bây giờ, hãy dùng custom specifier "#".
d.ToString("#.##", CultureInfo.InvariantCulture)
Dưới đây là các ví dụ khác.
Ví dụ
using System;
using System.Globalization;
class Demo {
static void Main() {
double d;
d = 4.2;
Console.WriteLine(d.ToString("#.##", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0:#.##}", d));
d = 345;
Console.WriteLine(d.ToString("#####"));
Console.WriteLine(String.Format("{0:#####}", d));
d = 74567989;
Console.WriteLine(d.ToString("[##-##-##-##]"));
Console.WriteLine(String.Format("{0:[##-##-##-##]}", d));
}
}
Kết quả
4.2 4.2 345 345 [74-56-79-89] [74-56-79-89]