JSTL formatNumber Example:
To display the numbers on JSP in proper format, you can use the <fmt:formatNumber> tag like this:
<%@ 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>
As you can see above, in the JSTL formatNumber tag, var attribute is used to define the variable than needs to be formatted. Proper formatting needs help of other attributes from formatNumber tag.
Attributes of <fmt:formatNumber> tag are:
1. var:This attribute provides numeric value to be formatted.
2. type: This attribute specifies whether the value is to be formatted as number, currency, or percentage.
3. maxFractionDigits: This attribute provides maximum number of digits in the fractional portion of the formatted output.
4. minFractionDigits : This attribute provides Minimum number of digits in the fractional portion of the formatted output.
5. pattern: This attribute provides custom formatting pattern.
6. value: This attribute provides Numeric value to be formatted.
7. scope: This attribute provides scope of var.
8. currencyCode: This attribute provides ISO 4217 currency code. Applied only when formatting currencies (i.e. if type is equal to “currency”). Ignored otherwise.
9. currencySymbol: This attribute provides Currency symbol. Applied only when formatting currencies (i.e. if type is equal to “currency”); ignored otherwise.
10. groupingUsed: This attribute specifies whether the formatted output will contain any grouping separators..
11. maxIntegerDigits: This attribute provides Maximum number of digits in the integer portion of the formatted output.
12. minIntegerDigits: This attribute provides Minimum number of digits in the integer portion of the formatted output.