我需要将 $ 符号附加到指定宽度且右对齐的字段中的浮点值。
使用 system.out.printf("$%8.2f", r.getPrice()) 很容易,但这给了我一个左对齐的 $ 符号,而我的浮点值右对齐,例如 $ 23.99(在 $ 符号和浮点值之间有未使用的宽度指定的空格)而不是 $23.99(在浮点值和 $ 符号的左侧都有未使用的宽度指定的空格)。
请注意,分配给该字段的值来自类“getter”(不知道这是否有区别)。
代码如下:
list.stream()
.forEach(r ->
System.out.printf("%4d %-15s %-27s %6d %8.2f\n", r.getId(),
r.getDepartment(), r.getDescription(), r.getQuantity(), r.getPrice())
);
最佳答案
有一种效果很好的区域设置敏感的习惯用法:
使用NumberFormat.getCurrencyInstance() :
import java.text.NumberFormat;
// Get a currency format for the current locale.
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println(fmt.format(120.00)); //replace here your variable
如果您当前的区域设置在美国,println
将打印 $120.00
另一个例子:
import java.text.NumberFormat;
import java.util.Locale;
Locale locale = new Locale("en", "UK");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
System.out.println(fmt.format(120.00));
这将打印:£120.00
关于java - 如何将 $ 符号附加到指定宽度且右对齐的字段中的浮点值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46385641/