6

我知道如何使用逗号printf作为分组分隔符以像这样的格式打印值 1,000,000.00

以我使用命令的方式打印

System.out.printf ("%,.2f", value);

但是如何使用空格作为分组分隔符来格式化值 1 000 000.00

我试图找到解决方案,但使用DecimalFormat“现在看”的解决方案让我变得复杂(初级)。 有没有像逗号一样简单的方法来做到这一点

4

3 回答 3

8

快速回答:

String result = String.format("%,.2f", value).replace(".", " ");
System.out.println(result);

(假设您使用的是 Java 1.5 或更高版本)。

使用DecimalFormat

DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.getDefault());
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
String.format(symbols.getGroupingSeparator(), ' ')

甚至更好:

symbols.setGroupingSeparator(' ');
f = new DecimalFormat("###,###.00", symbols);
System.out.println(f.format(value));
于 2012-11-09T11:35:19.170 回答
1

Printf 不处理这个。使用 println insted。来自oracle的示例:

DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale);
unusualSymbols.setDecimalSeparator('|');
unusualSymbols.setGroupingSeparator('^');

String strange = "#,##0.###";
DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols);
weirdFormatter.setGroupingSize(4);

String bizarre = weirdFormatter.format(12345.678);
System.out.println(bizarre);

out : 1^2345|678

将浮点数转换为字符串:

println 使用FloatingDecimal

printf 使用FormattedFloatingDecimal

但是我没有时间深入研究为什么这些类是不同的。享受阅读 :)

于 2012-11-09T11:35:56.167 回答
0

如果你想这样做,你应该使用 Decimalformat 这将是你的解决方案

DecimalFormat f = new DecimalFormat("#0,000.00");

f.格式(13000);

在这里稍微解释一下:逗号后的零数量将为您提供 DecimalFormat 将在其中插入一个点的数字数量。点后的零数量是 DecimalFormat 将写入的小数数量

编辑:哦,我刚刚看到你想在那里有空间:

因为 f.format 将返回一个字符串,您可以简单地添加.replace("\\.", " ");

方法。这将用空格替换所有写在那里的点

于 2012-11-09T11:25:37.310 回答