How to format percentages in JSP?

JSPJava 8Object Oriented ProgrammingProgramming

The <fmt:formatNumber> tag is used to format numbers, percentages, and currencies.

Attribute

The <fmt:formatNumber> tag has the following attributes −

AttributeDescriptionRequiredDefault
ValueNumeric value to displayYesNone
typeNUMBER, CURRENCY, or PERCENTNoNumber
patternSpecify a custom formatting pattern for the output.NoNone
currencyCodeCurrency code (for type = "currency")NoFrom the default locale
currencySymbolCurrency symbol (for type = "currency")NoFrom the default locale
groupingUsedWhether to group numbers (TRUE or FALSE)Notrue
maxIntegerDigitsMaximum number of integer digits to printNoNone
minIntegerDigitsMinimum number of integer digits to printNoNone
maxFractionDigitsMaximum number of fractional digits to printNoNone
minFractionDigitsMinimum number of fractional digits to printNoNone
varName of the variable to store the formatted numberNoPrint to page
scopeScope of the variable to store the formatted numberNopage

Example

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<html>
   <head>
      <title>JSTL fmt:formatNumber Tag</title>
   </head>
   <body>
      <h3>Number Format:</h3>
      <c:set var = "balance" value = "120000.2309" />
      <p>Formatted Number (1): <fmt:formatNumber type = "percent" maxIntegerDigits="3" value = "${balance}" /></p>
      <p>Formatted Number (2): <fmt:formatNumber type = "percent" minFractionDigits = "10" value = "${balance}" /></p>
      <p>Formatted Number (3): <fmt:formatNumber type = "percent" maxIntegerDigits = "3" value = "${balance}" /></p>
   </body>
</html>

The above code will generate the following result −

Number Format:
Formatted Number (1): 023%
Formatted Number (2): 12,000,023.0900000000%
Formatted Number (3): 023%
raja
Published on 22-Mar-2019 10:30:14
Advertisements