Java中MessageFormat.format 与千位符
1、当占位符替换的目标值为String类型时:结果保存不变
2、当占位符替换的目标值为int类型时:会自动转换为国家化数字 (国家化数字:在数字达到4位以上的时候会在千位后面加逗号)如:输入1000,转换后是1,000;
看下面的例子01:
@Test
public void MessageFormat_Test () {
String format = "{0}年{1}月";
System.out.println(MessageFormat.format(format, 2020, 4));
}
输出结果为:
2,020年4月
下面的例子02:
@Test
public void MessageFormat_Test () {
String format = "{0}年{1}月";
System.out.println(MessageFormat.format(format, "2020", "04"));
}
输出结果为:
2020年04月
另外,MessageFormat.format占位符是可以加格式化描述的:
下面的例子03:
@Test
public void MessageFormat_Test () {
String format = "{0,number,#}年{1}月";
System.out.println(MessageFormat.format(format, 2020, "04"));
format = "{0,number,#.00}年{1}月";
System.out.println(MessageFormat.format(format, 2020, "04"));
}
输出结果为:
2020年04月
2020.00年04月
注意:占位符中指定了number了,则目标值类型必须为数值型,否则异常。如下例子04:
@Test
public void MessageFormat_Test () {
String format = "{0,number,#}年{1}月";
MessageFormat.format(format, "2020", "04"); // java.lang.IllegalArgumentException: Cannot format given Object as a Number
MessageFormat.format(format, new BigDecimal("2020"), "04"); // OK
MessageFormat.format(format, new Double("2020"), "04"); // OK
MessageFormat.format(format, new Float("2020"), "04"); // OK
MessageFormat.format(format, 2020, "04"); // OK
}