gpt4 book ai didi

java - Java 中的 printf 格式化

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:00:29 24 4
gpt4 key购买 nike

这是我的代码:

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 中使用时它似乎无法正常工作,而它在我程序的另一个区域中正常工作。关于如何解决此问题的任何想法?

最佳答案

问题是您将价格指定为小数点前固定的 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

关于java - Java 中的 printf 格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29527969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com