JSTL Core < fmt:formatNumber > 标签
<fmt:formatNumber> 标签用于格式化数字,百分比和货币。
属性:
<fmt:formatNumber> 标签具有如下所示属性:
| 属性 | 描述 | 是否必需 | 默认值 |
|---|---|---|---|
| value | 显示的数值 | 是 | 无 |
| type | 数值、货币或百分比 | 否 | 数值 |
| pattern | 为输出指定一个自定义格式模式 | 否 | 无 |
| currencyCode | Currency 代码 (for type="currency") | 否 | 来自默认语言环境 |
| currencySymbol | Currency 符号 (for type="currency") | 否 | 来自默认语言环境 |
| groupingUsed | 是否将数值分组 (TRUE or FALSE) | 否 | true |
| maxIntegerDigits | 输出的整数位数的最大值 | 否 | 无 |
| minIntegerDigits | 输出的整数位数的最小值 | 否 | 无 |
| maxFractionDigits | 输出的小数位数的最大值 | 否 | 无 |
| minFractionDigits | 输出的小数位数的最小值 | 否 | 无 |
| var | 存储格式化数字的变量名 | 否 | 页面输出 |
| scope | 存储格式化数字的变量范围 | 否 | 页面 |
-
如果 type 属性是百分比或数字,那么你可以使用一些数字-格式化属性。maxIntegerDigits 和 minIntegerDigits 属性允许你指定数字的非小数部分的大小。如果实际数字超过了 maxIntegerDigits,那么数字就会被截断。
-
属性同样允许你确定使用多少为小数。minFractionalDigits 和 maxFractionalDigits 属性允许你指定小数位数。如果数字超过了小数位数的最大值,那么数字就会被截断。
-
分组可以用来在成千上万组之间插入逗号。通过将 groupingIsUsed 属性设置为真或假来指定分组。当分组与 minIntegerDigits 一起使用时,必须多加小心来得到你预想的结果。
- 你可能会选择使用 pattern 属性。该属性可以包含特殊字符,指定你有多喜欢编码的数字。下表展示了这些代码。
| Symbol | Description |
|---|---|
0 |
代表了一个数字。 |
E |
代表了指数形式。 |
# |
代表一个数字;显示 0 为缺席。 |
. |
作为十进制分隔符的一个占位符。 |
, |
作为分组分隔符的一个占位符。 |
; |
分隔形式 |
- |
作为默认的负数前缀。 |
% |
乘以 100 并作为百分比显示。 |
? |
乘以 1000 并作为千分比显示。 |
¤ |
代表了货币符号; 被动态的货币符号取代。 |
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