Java 数字格式化

标签 java

<分区>

使用以下代码将数字 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。您需要编写自己的格式化程序。

关于Java 数字格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30975982/

相关文章:

java - 当设置为 Android 4.0 时,Eclipse 无法识别 numberPassword?

java - Java Parallel Stream 与 ExecutorService 的性能对比

java - 使用 Spring Security 当用户不存在时如何显示错误消息?

java - ConcurrentHashMap 上的竞争条件问题

java - 使用 java 在终端中读取 postgres 表

java - ServletContextListener 还是 load-on-startup 是先执行?

java - 反转数组中的元素

java - 如何有效地使用重载和多态性

java - Java 声音缩放

java - 无法检查文件是否存在于 Web 项目中