当我们代码中使用MessageFormat类时,如果将Integer、Long等类型传入进去,可能会被格式化成带有逗号的数字,这里特别要小心,否则我们在将这样处理后的字符串带到数据库或其他地方使用时,就会报错。
具体来说:MessageFormat格式化数字,超过三位数的数字,格式化之后会自动变成国外数字的记法(百位之后每三位数字用逗号分隔),比如9999会变为9,999之类的。
看个例子:
public static void main(String[] args) {
System.out.println(MessageFormat.format("{0} {1}", 999,9999));
System.out.println(MessageFormat.format("{0} {1}", new Integer(999).toString(),new Integer(9999).toString()));
System.out.println(MessageFormat.format("{0} {1} {2}", 9999.999,99999.9999,99999.4444444));
}
//输出
999 9,999
999 9999
9,999.999 100,000 99,999.444
总结:使用MessageFormat格式化数字、日期的时候,传入的替换参数最好先转成我们所需要格式的字符串类型变量,否则容易被MessageFormat格式化成我们预期之外的结果。