ASP 內建 Round() 使用「銀行家捨入法」(四捨六入五成雙),不符合一般商業四捨五入習慣。FormatNumber() 提供標準四捨五入並支援豐富格式化選項,是處理貨幣、百分比、數字顯示的首選。
語法
FormatNumber(Expression [, NumDigitsAfterDecimal [, IncludeLeadingDigit [, UseParensForNegative [, GroupDigits]]]])
參數詳解
| 參數 | 型別 | 預設 | 說明 |
Expression | Variant | 必要 | 要格式化的數值運算式 |
NumDigitsAfterDecimal | Integer | -1 (系統區域設定) | 小數位數 |
IncludeLeadingDigit | Integer | -1 | -1/True 顯示前導 0 (如 0.5);0/False 不顯示 (.5) |
UseParensForNegative | Integer | -1 | -1/True 負數用括號 (如 (1.23));0/False 用負號 (-1.23) |
GroupDigits | Integer | -1 | -1/True 千分位分隔符;0/False 不分組 |
實際範例
<%
' 基本四捨五入
Response.Write FormatNumber(3.14159, 2) & "
" ' 3.14
Response.Write FormatNumber(3.145, 2) & "
" ' 3.15 (標準四捨五入)
Response.Write FormatNumber(3.5, 0) & "
" ' 4
Response.Write FormatNumber(2.5, 0) & "
" ' 3 (Round(2.5)=2 銀行家捨入)
' 貨幣格式
Response.Write FormatNumber(1234567.89, 2, -1, -1, -1) & "
" ' 1,234,567.89 (含千分位)
' 負數括號格式
Response.Write FormatNumber(-123.45, 2, -1, -1) & "
" ' (123.45)
Response.Write FormatNumber(-123.45, 2, -1, 0) & "
" ' -123.45
' 百分比 (乘 100 後格式化)
pct = 0.1234
Response.Write FormatNumber(pct * 100, 2) & "%" & "
" ' 12.34%
%>
Round() vs FormatNumber() 差異對照
| 數值 | Round() | FormatNumber(,0) | 說明 |
| 2.5 | 2 | 3 | Round 銀行家捨入,FormatNumber 標準四捨五入 |
| 3.5 | 4 | 4 | 同 |
| 1.005 | 1 | 1.01 (FormatNumber(,2)) | 浮點數精度問題,建議貨幣用整數分計算 |
最佳實務建議
- 金額計算:資料庫存「分」(整數),顯示時
FormatNumber(amount/100, 2),避免浮點數誤差。
- 顯示格式:統一用
FormatNumber 而非手動字串拼接。
- 區域設定:預設參數 -1 依伺服器區域設定,跨區域部署建議明確指定參數。
- ASP.NET 遷移:改用
String.Format("{0:N2}", val) 或 val.ToString("N2") (C#)。