Recipe 24.12 Formatting Percentages in a JSP


Problem

You want to display a number as a percentage in a JSP.

Solution

Use the fmt:formatNumber tag.

Discussion

The JSTL's fmt:formatNumber tag can display a number the code provides in the tag's value attribute as a percentage. The value of the type attribute must be "percent" (not "percentage"). Example 24-13 passes the String ".51" to the value attribute. This code displays the text "51%" in the browser.

Example 24-13. Using the fmt:formatNumber tag in a JSP to display a percentage
 <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>  <%@ 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=".51" type="percent" />  </body> </html> 

Figure 24-8 shows the JSP's output.

Figure 24-8. A JSP displays a number formatted as a percentage
figs/jsjc_2408.gif

See Also

The Javadoc for the NumberFormat class: http://java.sun.com/j2se/1.4.1/docs/api/java/text/NumberFormat.html; Chapter 23 on the JSTL; Recipe 24.12 on formatting percentages 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