ภาพรวม
ตัวกำหนดรูปแบบ "#" (แฮช) ทำหน้าที่เป็น ตัวแทนหลัก (digit placeholder) หากมีหลักในตำแหน่งนั้น จะแสดงหลักนั้น หากไม่มี จะ ไม่แสดงอะไรเลย (ต่างจาก "0" ที่แสดง 0)
ตัวอย่างการใช้งาน
double d = 4.2;
d.ToString("#.##", CultureInfo.InvariantCulture); // "4.2" (ไม่แสดง 0 นำหน้าหรือท้าย)
ตัวอย่างโค้ดเต็ม
using System;
using System.Globalization;
class Demo
{
static void Main()
{
double d = 4.2;
Console.WriteLine(d.ToString("#.##", CultureInfo.InvariantCulture)); // 4.2
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0:#.##}", d)); // 4.2
d = 345;
Console.WriteLine(d.ToString("#####")); // 345
Console.WriteLine(String.Format("{0:#####}", d)); // 345
d = 74567989;
Console.WriteLine(d.ToString("[##-##-##-##]")); // [74-56-79-89]
Console.WriteLine(String.Format("{0:[##-##-##-##]}", d)); // [74-56-79-89]
}
}
ผลลัพธ์
4.2 4.2 345 345 [74-56-79-89] [74-56-79-89]
ความแตกต่างระหว่าง # และ 0
| ตัวกำหนด | พฤติกรรม | ตัวอย่าง (123.4) |
|---|---|---|
| # | แสดงหลักที่มีจริง ไม่แสดง 0 นำหน้า/ท้าย | "##.##" → "123.4" |
| 0 | แสดง 0 หากไม่มีหลักในตำแหน่งนั้น | "000.00" → "123.40" |