我想将double值格式化为具有
的样式特别使用java.util.Formatter类
示例: -
double amount = 5896324555.59235328;
String finalAmount = "";
// Some coding
System.out.println("Amount is - " + finalAmount);
应该像: -
Amount is - $ 5,896,324,555.60
我搜索过,但是我无法理解Oracle文档或其他教程,我发现这个链接非常接近我的要求,但它不是用Java - How to format double value into string with 2 decimal places after dot and with separators of thousands?
答案 0 :(得分:8)
如果您需要使用java.util.Formatter
,这将有效:
double amount = 5896324555.59235328;
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("$ %(,.2f", amount);
System.out.println("Amount is - " + sb);
扩展了Formatter
页面的示例代码。
答案 1 :(得分:3)
我强烈建议您使用内置货币格式化程序的java.text.NumberFormat
,而不是使用java.util.Formatter
:
double amount = 5896324555.59235328;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String finalAmount = formatter.format(amount);
System.out.println("Amount is - " + finalAmount);
// prints: Amount is - $5,896,324,555.59
答案 2 :(得分:2)
您可以使用printf
和格式规范,例如
double amount = 5896324555.59235328;
System.out.printf("Amount is - $%,.2f", amount);
输出
Amount is - $5,896,324,555.59
要达到60美分,你需要59.5
美分(或更多)。