简体   繁体   English

如何在GWT中使用特定语言环境将字符串转换为Double?

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

In java this is easy to do: 在Java中,这很容易做到:

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

However, I can't seem to do the same thing in GWT. 但是,我似乎无法在GWT中执行相同的操作。 First I incorporated the locale in MyModule.gwt.xml 首先,我将语言环境合并到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; 还存在NumberFormat类: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. 此处的默认表示固定的语言环境,与“ en_US”非常相似,浏览器或应用程序未选择默认的语言环境。

It seems there is no way to set the NumberFormat to accept a different locale. 似乎没有办法将NumberFormat设置为接受其他语言环境。 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 尝试将<meta name='gwt:property' content='locale=sl_SI' />到html主机页面

Here's an explanation on why it works like this: https://stackoverflow.com/a/16295300/572830 这是为什么这样工作的解释: https : //stackoverflow.com/a/16295300/572830

Here's the broader and detailed explanation: https://developers.google.com/web-toolkit/doc/latest/DevGuideI18nLocale 以下是更广泛和详细的说明: https : //developers.google.com/web-toolkit/doc/latest/DevGuideI18nLocale

Unfortunately, not. 不幸的是,不是。 Locale specific code on the client is very limited in GWT. 客户端上特定于语言环境的代码在GWT中非常有限。 You can try to use native JavaScript (with all the drawbacks). 您可以尝试使用本机JavaScript(具有所有缺点)。

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 + ']' 创建一个与任何非小数点或数字匹配的否定模式,即: '[^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. 对于格式化,我没有一个好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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