[ Team LiB ] Previous Section Next Section

Recipe 24.11 Formatting Percentages in a Servlet

Problem

You want to format numbers as percentages and display them in a servlet.

Solution

Use the java.txt.NumberFormat class and its static getPercentInstance( ) method.

Discussion

Example 24-12 uses the NumberFormat.getPercentInstance( ) method, with the user's locale as an argument, to get a NumberFormat type for displaying a number as a percentage. The code in Example 24-12 calls the NumberFormat's format( ) method, with a number as an argument.

The format( ) method displays the number 51 as "5100%"; a double type including the decimal point, such as 0.51 produces the intended result (51%).


Example 24-12. Using NumberFormat to display a percentage in a servlet
package com.jspservletcookbook;           

import java.text.NumberFormat;

import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.*;
import javax.servlet.http.*;

public class PerLocaleServlet extends HttpServlet {

  public void doGet(HttpServletRequest request,
  HttpServletResponse response)
  throws ServletException, java.io.IOException {
    
      //Get the client's Locale
      Locale locale = request.getLocale( );

      ResourceBundle bundle = ResourceBundle.getBundle(
      "i18n.WelcomeBundle",locale);

      String welcome =  bundle.getString("Welcome");
   
      NumberFormat nft = NumberFormat.getPercentInstance(locale);

      String formatted = nft.format(0.51);
   
      //Display the locale
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );

      out.println("<html><head><title>"+welcome+"</title></head><body>");
      
      out.println("<h2>"+bundle.getString("Hello") + " " +
        bundle.getString("and") + " " +
          welcome+"</h2>");
      
      
      out.println("Locale: ");
      out.println( locale.getLanguage( )+"_"+locale.getCountry( ) );
      
      out.println("<br /><br />");

      out.println("NumberFormat.getPercentInstance( ): "+formatted);
      
      out.println("</body></html>");
      
     } //doGet

//implement doPost( ) to call doGet( )...

}

Figure 24-7 shows the servlet's output in a browser.

Figure 24-7. The browser displays a percentage for a certain locale
figs/jsjc_2407.gif

See Also

The Javadoc for the NumberFormat class: http://java.sun.com/j2se/1.4.1/docs/api/java/text/NumberFormat.html; Recipe 24.12 on formatting percentages in a JSP.

    [ Team LiB ] Previous Section Next Section