如何在Java 11中使用不受支持的语言环境以及String.format()中的数字 [英] How to use unsupported Locale in Java 11 and numbers in String.format()

查看:97
本文介绍了如何在Java 11中使用不受支持的语言环境以及String.format()中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过 String.format()输出数字时,如何在 JAVA 11 中使用不受支持的语言环境(例如 ar-US )?

How can I use an unsupported Locale (eg. ar-US) in JAVA 11 when I output a number via String.format()?

Java 8 中,此方法很好用(尝试 jdoodle 选择JDK 1.8.0_66 ):

In Java 8 this worked just fine (try jdoodle, select JDK 1.8.0_66):

Locale locale = Locale.forLanguageTag("ar-US");
System.out.println(String.format(locale, "Output: %d", 120));
// Output: 120

Java 11 起,输出结果显示在东部阿拉伯数字中(尝试 jdoodle 使用默认的JDK 11.0.4 ):

Since Java 11 the output is in Eastern Arabic numerals (try jdoodle, use default JDK 11.0.4):

Locale locale = Locale.forLanguageTag("ar-US");
System.out.println(String.format(locale, "Output: %d", 120));
// Output: ١٢٠

看来,此问题来自区域设置数据提供者表格 JRE Java中的本地化更改@mcarth的第9张).以下是受支持的语言环境的列表: JDK 11支持的语言环境

It seems, this problem comes from the switch in the Locale Data Providers form JRE to CLDR (source: Localization Changes in Java 9 by @mcarth). Here is a list of supported locales: JDK 11 Supported Locales

更新

我将问题示例更新为 ar-US ,因为之前的示例没有意义.想法是在该特定国家/地区采用一种有意义的格式.在示例中,将是美国( US ).

I updated the questions example to ar-US, as my example before didn't make sense. The idea is to have a format which makes sense in that given country. In the example it would be the United States (US).

推荐答案

此行为符合被视为首选 Locale 的CLDR.为了确认这一点,可以使用以下命令在Java-8中执行相同的代码段

The behavior conforms to the CLDR being treated as the preferred Locale. To confirm this, the same snippet in Java-8 could be executed with

-Djava.locale.providers=CLDR

如果您退后来看 JEP 252:默认情况下使用CLDR语言环境数据,详细信息如下:

If you step back to look at the JEP 252: Use CLDR Locale Data by Default, the details follow :

默认查找顺序为CLDR,COMPAT,SPI,其中COMPAT在JDK 9中指定JRE的语言环境数据.无法提供请求的语言环境数据,搜索将继续进行下一个提供者.

The default lookup order will be CLDR, COMPAT, SPI, where COMPAT designates the JRE's locale data in JDK 9. If a particular provider cannot offer the requested locale data, the search will proceed to the next provider in order.

因此,简而言之,如果您真的不希望默认行为是Java-11,则可以使用VM参数更改查找顺序

So, in short if you really don't want the default behaviour to be that of Java-11, you can change the order of lookup with the VM argument

-Djava.locale.providers=COMPAT,CLDR,SPI

可能进一步帮助您更多地了解选择使用CLDR选择正确的语言!

What might help further is understanding more about picking the right language using CLDR!

这篇关于如何在Java 11中使用不受支持的语言环境以及String.format()中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆