Smalcat
Smalcat

Reputation: 231

How do I convert a String to Double in GWT using a specific locale?

In java this is easy to do:

NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
myNumber = nf.parse(myString);

However, I can't seem to do the same thing in GWT. First I incorporated the locale in MyModule.gwt.xml

<inherits name="com.google.gwt.i18n.I18N"/>
<extend-property name="locale" values="sl_SI"/>

There also exists the NumberFormat class: com.google.gwt.i18n.client.NumberFormat; which uses the "default" locale. Default here means a fixed locale that is very similar to "en_US" and not default chosen by the browser or application.

It seems there is no way to set the NumberFormat to accept a different locale. Quite frankly, I dont see any point then.

Am I missing something?

Upvotes: 0

Views: 1004

Answers (2)

Christian Achilli
Christian Achilli

Reputation: 5707

Try adding <meta name='gwt:property' content='locale=sl_SI' /> to the html host page

Here's an explanation on why it works like this: https://stackoverflow.com/a/16295300/572830

Here's the broader and detailed explanation: https://developers.google.com/web-toolkit/doc/latest/DevGuideI18nLocale

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328624

Unfortunately, not. Locale specific code on the client is very limited in GWT. You can try to use native JavaScript (with all the drawbacks).

But I found that it's easier to just call a server method in such cases. For one, I usually don't have to convert many values and the rate I need this method is low, so the overkill of send bytes over the network is bearable in this case.

If this isn't an option for you and you only need to be able to parse such a number, I suggest to take the format for the locale apart. This is easier than it looks if you follow this approach:

  • Figure out what the decimal point (comma or point) is.
  • Create a negative pattern which matches anything that isn't the decimal point or digits, i.e.: '[^0-9' + decimalPoint + ']'
  • Use this pattern to remove anything that matches from the string
  • Replace decimal point with .

This allows parsing. For formatting, I don't have a good solution.

Upvotes: 0

Related Questions