java String.format:带有本地化的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13763700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:54:03  来源:igfitidea点击:

java String.format: numbers with localization

javalocalizationnumbersstring-formatting

提问by wziska

Is it possible to localize numbers in String.format call the same way as NumberFormat.format does?

是否可以像 NumberFormat.format 一样本地化 String.format 调用中的数字?

I've expected it simply to use

我希望它只是使用

String.format(locale, "%d", number)

but this doesn't return the same result as if using NumberFormat. For example:

但这不会返回与使用 NumberFormat 相同的结果。例如:

String.format(Locale.GERMAN, "%d", 1234567890) 

gives: "1234567890", while

给出:“1234567890”,而

NumberFormat.getNumberInstance(Locale.GERMAN).format(1234567890)

gives: "1.234.567.890"

给出:“1.234.567.890”

If it can't be done, what's recommended way for localizing text including numbers?

如果无法完成,本地化包括数字在内的文本的推荐方法是什么?

回答by serg10

From the documentation, you have to:

文档中,您必须:

  • supply a locale (as you are doing in your example)
  • include the ',' flag to show locale-specific grouping separators
  • 提供语言环境(正如您在示例中所做的那样)
  • 包括“,”标志以显示特定区域设置的分组分隔符

So your example would become:

所以你的例子会变成:

String.format(Locale.GERMAN, "%,d", 1234567890) 

Note the additional ',' flag before the 'd'.

请注意“d”之前的附加“,”标志。

回答by JB Nizet

An alternative to String.format()is to use MessageFormat:

另一种方法String.format()是使用 MessageFormat:

MessageFormat format = new MessageFormat("The number is {0, number}", Locale.GERMAN);
String s = format.format(new Object[] {number});