{0}和{0,number,integer}有什么区别
-
12-12-2019 - |
题
我试图了解更多关于Java的 信息格式 实用程序,在我们的代码库和其他地方的例子中,我看到两者 {0}
和 {0,number,integer}
被用于数字,但我不确定哪个,如果有的话,更可取。
快速测试打印差异:
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.util.Locale;
public class MessageFormatTest
{
public static void main(String[] args){
MessageFormat simpleChoiceTest = new MessageFormat("{0}");
MessageFormat explicitChoiceTest = new MessageFormat("{0,number,integer}");
int[] set = new int[]{0,1,4,5,6,10,10000,24345};
Locale[] locs = new Locale[]{Locale.US,Locale.UK,Locale.FRANCE,Locale.GERMANY};
for(Locale loc : locs){
simpleChoiceTest.setLocale(loc);
explicitChoiceTest.setLocale(loc);
for(int i : set){
String simple = simpleChoiceTest.format(new Object[]{i});
String explicit = explicitChoiceTest.format(new Object[]{i});
if(!simple.equals(explicit)){
System.out.println(loc+" - "+i+":\t"+simple+
"\t"+NumberFormat.getInstance(loc).format(i));
System.out.println(loc+" - "+i+":\t"+explicit+
"\t"+NumberFormat.getIntegerInstance(loc).format(i));
}
}
}
}
}
产出:
fr_FR - 10000: 10 000 10 000
fr_FR - 10000: 10,000 10 000
fr_FR - 24345: 24 345 24 345
fr_FR - 24345: 24,345 24 345
de_DE - 10000: 10.000 10.000
de_DE - 10000: 10,000 10.000
de_DE - 24345: 24.345 24.345
de_DE - 24345: 24,345 24.345
这让我感到惊讶,如果有什么我会料到 {0}
不做任何事情的数量,并为 {0,number,integer}
以将其正确地本地化。相反,两者都得到本地化,但似乎显式形式总是使用en_US本地化。
根据链接的文档, {0}
获得通过 NumberFormat.getInstance(getLocale())
虽然显式表单使用 NumberFormat.getIntegerInstance(getLocale())
.然而,当我直接调用这些(输出中的最后一列)时,两者似乎都是相同的,并且都正确本地化。
我在这里错过了什么?
解决方案
你说得对。当您使用"MessageFormat("{0,number,integer}")"时,formatter在初始化时使用默认区域设置(en_US),数字被标记为在默认区域设置(en_US)中使用整数格式,因为下面的代码是在初始化期间执行的。
// this method is internally called at the time of initialization
MessageFormat.makeFormat()
// line below uses default locale if locale is not
// supplied at initialization (constructor argument)
newFormat = NumberFormat.getIntegerInstance(locale);
由于之后要设置区域设置,因此对分配给数字的格式模式没有影响。如果您想在数字格式中使用所需的区域设置,请在初始化时使用区域设置参数,例如。下面:
MessageFormat test = new MessageFormat("{0,number,integer}", Locale.FRANCE);
其他提示
在我看来,这是一个Java错误(界面错误)或文档问题。您应该在Oracle上打开一个新问题来纠正这一点。
正如Yogendra Singh所说,格式化程序(DecimalFormat)的实例是在MessageFormat构造函数时创建的。
MessageFormat simpleChoiceTest = new MessageFormat("{0}");
System.out.println(simpleChoiceTest.getFormatsByArgumentIndex()[0]);
//Prints null
MessageFormat explicitChoiceTest = new MessageFormat("{0,number,currency}");
System.out.println(explicitChoiceTest.getFormatsByArgumentIndex()[0]);
//Prints java.text.DecimalFormat@67500
当MessageFormat。调用setLocale时,它不会更改其内部格式化程序的区域设置。
至少应该更改文档以反映此问题。
那是我的java版本:java版本"1.7.0_07" Java(TM)SE运行时环境(build1.7.0_07-b11)