[ Team LiB ] |
![]() ![]() |
Recipe 24.10 Formatting Currencies in a JSPProblemYou want to format currency values in a JSP. SolutionUse the JSTL tag fmt:formatNumber. DiscussionThe fmt:formatNumber tag is designed to display a currency value based on the visitor's locale. Example 24-11 first uses the taglib directive to make the JSTL 1.0 formatting library available to the JSP. Example 24-11. formatting a number using the JSTL 1.0 tags<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <%-- the formatting library includes fmt:formatNumber --%> <%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %> <html> <head><title> <fmt:message key="Welcome" /></title></head> <body> <h2> <fmt:message key="Hello" /> <fmt:message key="and" /> <fmt:message key="Welcome" /></ h2> Locale: <c:out value="${pageContext.request.locale.language}" />_<c:out value="${pageContext.request.locale.country}" /> <br /><br /> <fmt:formatNumber value="1000000" type="currency" /> </body> </html> The fmt:formatNumber tag is quite straightforward. The value attribute takes the number you want to format as a currency, and the value of the type attribute must be "currency." The text representing the formatted number then replaces the tag when a browser displays the JSP's output. The JSP in Example 24-11 displays the same browser information as shown in Figure 24-6 of the prior recipe. See AlsoChapter 23 on the JSTL; the Javadoc for the NumberFormat class: http://java.sun.com/j2se/1.4.1/docs/api/java/text/NumberFormat.html; Recipe 24.9 on formatting currencies in a servlet. ![]() |
[ Team LiB ] |
![]() ![]() |