January 11, 2009

將數字轉為以千為單位並用逗號區分的方法

當我們有一數字65536想以65,536來顯示時,我們可以下列函數做處理
String.Format("{0:N0}", 65536)
上述方法可得到一字串65,536,其中{0:N0}的0表示要顯示的小數點位數
以上述範例來看,如果我們改為
String.Format("{0:N2}", 65536)
則得到的結果為65,536.00

如果要以上述所得字串轉回去純數值資料的話, 可以用
Integer.Parse("65,536", System.Globalization.NumberStyles.AllowThousands)
有時在GridView中想把顯示出的數字以千為區分時,我們可以在BoundField中,將其DataFormatString屬性設為{0:N0},並把HtmlEncode屬性設為false,即可得到前述結果。

補充
經hatelove大提醒得知如果要parse的字串含小數點,如"65,536.00",則無法使用System.Globalization.NumberStyles.AllowThousands須改用System.Globalization.NumberStyles.Number
以下是測試結果
System.Globalization.NumberStyles.AllowThousands僅適用於無小數點的數值字串,如"65,536";而System.Globalization.NumberStyles.Number則適用於無小數點和有小數點的數值字串,如"65,536"或"65,536.00"。

參考
為何System.Globalization.NumberStyles.Number可允許有小數點和無小數點的情況?大家可以參考MSDN。
http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles.aspx

在說明表格Number欄位中有提到"Indicates that the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowTrailingSign, AllowDecimalPoint, and AllowThousands styles are used. This is a composite number style. "
所以Number具有AllowThousands及AllowDecimalPoint的功能,可同時轉換有小數點及無小數點的情況。

No comments: