问题描述
当我通过 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 到 CLDR (来源: 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 :
因此,简而言之,如果您真的不希望默认行为是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()中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!