Recipe 24.9 Formatting Currencies in a Servlet


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


Use the java.text.NumberFormat class.


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, {  //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"); 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

See Also

The Javadoc for the NumberFormat class:; Recipe 24.10 on formatting currencies in a JSP.

Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: