简体   繁体   中英

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?

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

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, ie: '[^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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM