Recipe 24.12 Formatting Percentages in a JSP


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


Use the fmt:formatNumber tag.


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="" prefix="c" %>  <%@ taglib uri="" 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="${}" />  <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

See Also

The Javadoc for the NumberFormat class:; 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 © 2008-2017.
If you may any questions please contact us: