Recipe 24.10 Formatting Currencies in a JSP


Problem

You want to format currency values in a JSP.

Solution

Use the JSTL tag fmt:formatNumber .

Discussion

The 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 Also

Chapter 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.



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net