当我试图格式化我的输出到两个小数位时,我一直收到错误。例如在java中我想要5.0中的5.00。下面的代码一直显示格式错误。
System.out.printf("%-40s %-6.2f", "Borrowing Fee: $", borrowingFee + "\n");我想让它输出:Borrowing Fee: $5.00
发布于 2016-10-25 04:17:03
为什么会有这么复杂的代码?如果你有一个浮点数作为输入,你可以这样做:
public static void main(String[] args) {
float borrowingFee = 5.0F;
System.out.printf("Borrowing Fee: $%.2f ", borrowingFee );
}它应该根据您的区域设置返回Borrowing Fee: $5,00或Borrowing Fee: $5.00。
发布于 2016-10-25 04:53:38
您可以使用DecimalFormat。它有许多实用函数。
public static String getFormattedAmountWithDecimals(String value){
String tmpDouble = "";
DecimalFormat formatter = new DecimalFormat("###,###,###.00");
try {
tmpDouble = formatter.format(Double.parseDouble(value));
if(tmpDouble.equalsIgnoreCase(".00")){
tmpDouble = "0.00";
}
}catch(Exception e) {
// System.out.println(e.toString());
}
return tmpDouble;
} 发布于 2016-10-25 04:18:29
如果您一直使用C编程,则格式化打印与C相同。尝试如下所示:
System.out.printf("Borrowing Fee: $%.2f",borrowingFee );https://stackoverflow.com/questions/40226699
复制相似问题