使用以下代码将数字 234156.123 格式化为 #,##,###.### 将格式化为 234,156.123 但它应该格式化为
2,34,156.123
小数位符合模式,而小数点前的数字未按预期格式化。
写的代码如下
String pattern = "#,##,###.###";
double number = 234156.123;
DecimalFormat decimalFormat = new DecimalFormat(pattern);
String format = decimalFormat.format(number);
System.out.println(format);
结果:
234,156.123
预期结果:
2,34,156.123
不幸的是,DecimalFormat 无法满足您的要求。
来自Javadoc :
The grouping size is a constant
number of digits between the grouping characters, such as 3 for
100,000,000 or 4 for 1,0000,0000. If you supply a pattern with
multiple grouping characters, the interval between the last one and
the end of the integer is the one that is used. So "#,##,###,####" ==
"######,####" == "##,####,####".
您想要的行为具有非常量组大小 - 3 前面有 2 前面有 1。您需要编写自己的格式化程序。