Java中的printf格式化

3

这是我的代码:

System.out.printf("\n%-10s%9s%11s%13s%9s\n",
            "yearBuilt","area(sqf)","price","replaceRoof","sqfPrice");

System.out.printf("\n%-10d%9.1f$%11.2f%13s$%8.2f\n",
            house1.getYear(),house1.getSquareFeet(),house1.getPrice(),house1.isRoofChangeNeeded(),house1.calcPricePerSqf());

这是我得到的输出结果:

    yearBuilt area(sqf)      price  replaceRoof sqfPrice


    1996         2395.0$  195000.00         true$   81.42

这是我想要的输出结果:

    yearBuilt area(sqf)       price  replaceRoof sqfPrice


    1996         2395.0  $195000.00         true   $81.42

我尝试使用DecimalFormat,但在printf内部使用时似乎无法正常工作,而在程序的其他区域正常工作。有没有什么方法可以解决这个问题?


3
请查看NumberFormat预定义格式 - adamdc78
2
这是一个写得非常好的问题!“这是我做的,这是我想要做的,这是我得到的结果。”希望能有更多像这样的问题。 - Bassinator
2个回答

1
问题在于您指定价格为小数点前的11位固定数字,而sqfPrice为8位数字,这会导致填充空格。
如果您分解打印语句:
System.out.printf("$%11.2f", 195000.0f);//print $  195000,0
System.out.printf("$%8.2f", 81.42f);//print $   81,42

您可能想使用NumberFormat而不是。
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);

假设您使用的是美国本地设置,
currencyFormatter.format(195000)

会输出$195,000.00


所以我添加了NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();并将我的printf更改为 System.out.printf("\n%-10d%9.1f%11.2s%13s%8.2s\n", house1.getYear(),house1.getSquareFeet(),currencyFormatter.format(house1.getPrice()),house1.isRoofChangeNeeded(),currencyFormatter.format(house1.calcPricePerSqf()));现在我得到的结果是:图片 - Kblo55
@Kblo55 这个输出有什么问题吗?货币符号似乎在您想要的位置。 - Jean-François Savard
它确实修复了美元符号的位置,但数字不正确。它显示的是$1和$8,而不是正确的金额。 - Kblo55
一个朋友帮我解决了问题。我不得不从我的printf格式中删除.1和.2,因为它们正在使用格式转换为字符串。感谢您的帮助! - Kblo55

0

在Java中,如果我们想要在printf语句中使用"$"符号,那就需要使用特殊的类。不过好消息是,在API中有这样的类可用。

可以从以下示例开始。

DecimalFormat currencyFormatter = new DecimalFormat("$000000.00");
System.out.printf("\n%-10d%9.1f%11.2f%13s%8.2f\n",house1.getYear(),house1.getSquareFeet(),currencyFormatter.format(house1.getPrice()),house1.isRoofChangeNeeded(),currencyFormatter.format(house1.calcPricePerSqf());

希望有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接