[ Team LiB ] Previous Section Next Section

Recipe 24.9 Formatting Currencies in a Servlet

Problem

You want to format a currency value according to the request's locale.

Solution

Use the java.text.NumberFormat class.

Discussion

The NumberFormat class can format a number, such as a long or double type, as a percentage. This class has a static getCurrencyInstance( ) method. This method can take a java.util.Locale object as a parameter, to display the currency according to the user's language setting.

Example 24-10 is a servlet that demonstrates the locale-sensitive display of a currency, by showing both the currency amount and the locale language and country code.

Example 24-10. Formatting a number as 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 CurrLocaleServlet 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.getCurrencyInstance(locale);

      String formattedCurr = nft.format(1000000);
   
      //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(formattedCurr);
      
      out.println("</body></html>");
      
     } //doGet

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

}

The NumberFormat class' format( ) method returns a String that represents the formatted currency. Figure 24-6 shows the servlet's output when requested by a browser where the user has set the language setting to the locale "en_GB" (English language, Great Britain).

Figure 24-6. A British visitor sees the formatted currency display of one million pounds
figs/jsjc_2406.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.10 on formatting currencies in a JSP.

    [ Team LiB ] Previous Section Next Section