[ Team LiB ] Previous Section Next Section

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="http://java.sun.com/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>

<head><title><fmt:message key="Welcome" /></title></head>
<h2><fmt:message key="Hello" /> <fmt:message key="and" /> <fmt:message key="Welcome" /></

Locale: <c:out value="${pageContext.request.locale.language}" />_<c:out 
value="${pageContext.request.locale.country}" /> 

<br /><br />

<fmt:formatNumber value=".51" type="percent" />

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

    [ Team LiB ] Previous Section Next Section