剛剛一個我負責的網站,出現了一個bug ,在之前沒有遇到過,而且生產環境運行了4/5年了也沒有發生該問題,今天發生了。所以查了一下<fmt:formatNumber>標簽的用法,自己記錄一下。
<fmt:formatNumber>標簽用於格式化數字,百分比,貨幣。
屬性
<fmt:formatNumber>標簽有如下屬性:
| 屬性 | 描述 | 是否必要 | 默認值 |
|---|---|---|---|
| value | 要顯示的數字 | 是 | 無 |
| type | NUMBER,CURRENCY,或 PERCENT類型 | 否 | Number |
| pattern | 指定一個自定義的格式化模式用與輸出 | 否 | 無 |
| currencyCode | 貨幣碼(當type="currency"時) | 否 | 取決於默認區域 |
| currencySymbol | 貨幣符號 (當 type="currency"時) | 否 | 取決於默認區域 |
| groupingUsed | 是否對數字分組 (TRUE 或 FALSE) | 否 | true |
| maxIntegerDigits | 整型數最大的位數 | 否 | 無 |
| minIntegerDigits | 整型數最小的位數 | 否 | 無 |
| maxFractionDigits | 小數點后最大的位數 | 否 | 無 |
| minFractionDigits | 小數點后最小的位數 | 否 | 無 |
| var | 存儲格式化數字的變量 | 否 | Print to page |
| scope | var屬性的作用域 | 否 | page |
如果type屬性為percent或number,那么您就可以使用其它幾個格式化數字屬性。maxIntegerDigits屬性和 minIntegerDigits屬性允許您指定整數的長度。若實際數字超過了maxIntegerDigits所指定的最大值,則數字將會被截斷。
有一些屬性允許您指定小數點后的位數。minFractionalDigits屬性和maxFractionalDigits屬性允許您指定小數點后的位數。若實際的數字超出了所指定的范圍,則這個數字會被截斷。
數字分組可以用來在每三個數字中插入一個逗號。groupingIsUsed屬性用來指定是否使用數字分組。當與minIntegerDigits屬性一同使用時,就必須要很小心地來獲取預期的結果了。
您或許會使用pattern屬性。這個屬性可以讓您在對數字編碼時包含指定的字符。接下來的表格中列出了這些字符。
| 符號 | 描述 |
|---|---|
| 0 | 代表一位數字 |
| E | 使用指數格式 |
| # | 代表一位數字,若沒有則顯示0 |
| . | 小數點 |
| , | 數字分組分隔符 |
| ; | 分隔格式 |
| - | 使用默認負數前綴 |
| % | 百分數 |
| ? | 千分數 |
| ¤ | 貨幣符號,使用實際的貨幣符號代替 |
| X | 指定可以作為前綴或后綴的字符 |
| ' | 在前綴或后綴中引用特殊字符 |
實例演示
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>JSTL fmt:formatNumber Tag</title>
</head>
<body>
<h3>Number Format:</h3>
<c:set var="balance" value="120000.2309" />
<p>Formatted Number (1): <fmt:formatNumber value="${balance}"
type="currency"/></p>
<p>Formatted Number (2): <fmt:formatNumber type="number"
maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (3): <fmt:formatNumber type="number"
maxFractionDigits="3" value="${balance}" /></p>
<p>Formatted Number (4): <fmt:formatNumber type="number"
groupingUsed="false" value="${balance}" /></p>
<p>Formatted Number (5): <fmt:formatNumber type="percent"
maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (6): <fmt:formatNumber type="percent"
minFractionDigits="10" value="${balance}" /></p>
<p>Formatted Number (7): <fmt:formatNumber type="percent"
maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (8): <fmt:formatNumber type="number"
pattern="###.###E0" value="${balance}" /></p>
<p>Currency in USA :
<fmt:setLocale value="en_US"/>
<fmt:formatNumber value="${balance}" type="currency"/></p>
</body>
</html>
運行結果如下:
NUMBER FORMAT: Formatted Number (1): £120,000.23 Formatted Number (2): 000.231 Formatted Number (3): 120,000.231 Formatted Number (4): 120000.231 Formatted Number (5): 023% Formatted Number (6): 12,000,023.0900000000% Formatted Number (7): 023% Formatted Number (8): 120E3 Currency in USA : $120,000.23
注意:
在格式化后如果不加屬性 groupingUsed =‘false’ 標簽將自動默認為true 。默認為true的效果就是1,000 。如果在el 表達式中要求有數字計算的話,將會報錯。因為其默認為string ,不可以計算。

