統計投票百分比時,7/17*100 = 41.17647...,保留兩位小數應為 41.18%。但 ASP 內建 Round 採用**「銀行家捨入法」(Banker's Rounding)**,導致 Round(1.5)=2、Round(2.5)=2 (非預期 3),與一般「四捨五入」認知不同。本文詳細比較三大函數差異並給出最佳實務。
| 輸入 | Round(n,0) | FormatNumber(n,0) | FormatPercent(n/100,0) | 說明 |
|---|---|---|---|---|
| 1.5 | 2 | 2 | 2% | |
| 2.5 | 2 ❌ | 3 ✅ | 3% | Round 進偶數 (銀行家) |
| 3.5 | 4 | 4 | 4% | |
| 4.5 | 4 ❌ | 5 ✅ | 5% | Round 進偶數 |
銀行家捨入法 (IEEE 754 標準):**五捨六入,五看前一位奇偶**——前一位為偶數則捨去,為奇數則進位。長期大量計算時正負誤差可抵消,適合財務/統計領域;但一般商業邏輯習慣「四捨五入」(≥5 進位),故 FormatNumber / FormatPercent 符合直覺。
' ❌ 易錯:手動乘 100 再 Round
Response.Write Round(7/17*100, 2) & "%" ' 可能因銀行家捨入產生誤差
' ❌ 尚可:FormatNumber 需手動加 %
Response.Write FormatNumber(7/17*100, 2) & "%"
' ✅ 最佳:FormatPercent 直接處理「乘100+加%+四捨五入」
Response.Write FormatPercent(7/17, 2) ' 輸出 "41.18%"
FormatPercent(Expression, [NumDigitsAfterDecimal], [IncludeLeadingDigit], [UseParensForNegative], [GroupDigits])
' Expression: 0~1 之間的小數 (如 7/17)
' NumDigitsAfterDecimal: 小數位數 (預設 -1 依區域設定,建議明確指定 2)
' 回傳:已乘 100 並附加 % 符號的字串
<%
TotalVotes = 17
AgreeVotes = 7
pct = FormatPercent(AgreeVotes / TotalVotes, 2) ' "41.18%"
Response.Write "贊同:" & AgreeVotes & " 票 (" & pct & ")<br>"
' 若需純數值 (不含 %) 供圖表用:
pctVal = CDbl(FormatNumber(AgreeVotes / TotalVotes * 100, 2)) ' 41.18
%>
Function RoundStd(val, decimals)
Dim factor : factor = 10 ^ decimals
RoundStd = Fix(val * factor + 0.5 * Sgn(val)) / factor
End Function
' 測試
Response.Write RoundStd(2.5, 0) ' 3
Response.Write RoundStd(4.5, 0) ' 5
Response.Write RoundStd(-2.5, 0) ' -3 (遠離零)
Round (銀行家捨入) 符合會計準則FormatNumber / FormatPercent (標準四捨五入) 符合用戶預期FormatPercent(ratio, decimals) 一步到位RoundStd 函數