How to specify the thousands and decimal separator used by GWT’s NumberFormat

gwtnumber-formatting

In the doc of GWT's NumberFormat class (http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/com/google/gwt/i18n/client/NumberFormat.html) I read:

"The prefixes, suffixes, and various symbols used for infinity, digits, thousands separators, decimal separators, etc. may be set to arbitrary values, and they will appear properly during formatting. However, care must be taken that the symbols and strings do not conflict, or parsing will be unreliable. For example, the decimal separator and thousands separator should be distinct characters, or parsing will be impossible."

My question is, how do I make sure that "." is used as thousands separator and "," as decimal separator independently of the user's locale settings?
In other words when I use the pattern "###,###,###.######" I want GWT to format the double value 1234567.89 always as "1.234.567,89" no matter what the user's locale is.

Best Answer

Solving this took some work. From the docs and source for NumberFormatter, it looks like only Locales can be used to set these values. They do say you can set the group separator but no such examples worked for me. While you might think the Java way to do this at the bottom would work since GWT emulates the DecimalFormat and DecimalFormalSymbols classes, they do not formally support them. Perhaps they will in the future. Further, they say in the LocaleInfo class that you can modify a locale, I found no such methods allowing this.

So, here is the Hack way to do it:

    NumberFormat.getFormat("#,##0.0#").format(2342442.23d).replace(",", "@");

Right way, but not yet GWT supported:

Use the decimal formatter:

    // formatter
    DecimalFormat format= new DecimalFormat();
    // custom symbol
    DecimalFormatSymbols customSymbols=new DecimalFormatSymbols();
    customSymbols.setGroupingSeparator('@');
    format.setDecimalFormatSymbols(customSymbols);
    // test
    String formattedString = format.format(2342442.23d);

The output:

2@342@442.23

Related Topic