作为printf中的分组分隔符的空格
我知道如何在printf
使用逗号作为分组分隔符以1,000,000.00
格式打印值
以那种方式打印我正在使用命令
System.out.printf ("%,.2f", value);
但如何使用空格作为分组分隔符来格式化值,如1 000 000.00
我试图找到解决方案,但现在使用DecimalFormat
解决方案让我复杂化(初学者级别)。 有逗号这样的简单方法吗?
快速回答:
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));
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
要将Float转换为String:
println使用FloatingDecimal
printf使用FormattedFloatingDecimal
但我没有时间深入研究为什么这些类不同。 享受阅读 :)
如果你想这样做,你应该使用Decimalformat这将是你的解决方案
DecimalFormat f = new DecimalFormat(“#0,000.00”);
f.format(13000);
这里有一点点的解释:逗号后面的零数量会给你DecimalFormat在那里插入一个点的数字量。 点后面的零数是DecimalFormat将写入的小数位数
编辑:哦,我刚看到你想在那里有空格:
因为f.format将返回一个String,你只需添加.replace("\\.", " ");
方法。 这将用空格替换写在那里的所有点