Java 有一个 DecimalFormat 类来处理类似的事情。
http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
所以你想添加到你的代码中
DecimalFormat df = new DecimalFormat("###,##0.00");
并将你的输出更改为
double totalwotax = (total * tax );
System.out.println("The tax for the subtotal is $" + df.format(totalwotax));
double totalandtax = (total + totalwotax);
System.out.println("The total for your bill with tax is $" + df.format(totalandtax));
这将确保您的美分小数点右侧恰好有两位数,并在左侧至少保留一位数,以防总数低于一美元。如果是 1,000 或以上,则会在正确的位置使用逗号进行格式化。如果您的总数高于 100 万,您可能需要将其更改为类似这样才能获得额外的命令
DecimalFormat df = new DecimalFormat("###,###,##0.00");
EDIT:因此Java还内置了对格式化货币的支持。忘记 DecimalFormatter 并使用以下内容:
NumberFormat nf = NumberFormat.getCurrencyInstance();
然后像使用 DecimalFormatter 一样使用它,但没有前面的美元符号(它将由格式化程序添加)
System.out.println("The total for your bill with tax is " + nf.format(totalandtax));
此外,此方法对区域设置敏感,因此如果您在美国,它将使用美元,如果在日本,它将使用日元,依此类推。