Format a number based on Locale in Java

Description

The following code shows how to format a number based on Locale.

Example


/*from   w  ww  . j  a  v a 2s.c  o  m*/
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;

public class Main {

  static public void localizedFormat(String pattern, double value, Locale loc) {
    NumberFormat nf = NumberFormat.getNumberInstance(loc);
    DecimalFormat df = (DecimalFormat) nf;
    df.applyPattern(pattern);
    String output = df.format(value);
    System.out.println(pattern + "  " + output + "  " + loc.toString());
  }

  static public void main(String[] args) {


    Locale[] locales = { new Locale("en", "US"), new Locale("de", "DE"),
        new Locale("fr", "FR") };

    for (int i = 0; i < locales.length; i++) {
      localizedFormat("###,###.###", 123456.789, locales[i]);
    }

  }
}




















Home »
  Java Tutorial »
    Data Format »




Java Formatter
Java Number Formatter