O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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>"); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required