printf formatting in Java



这是我的代码:

System.out.printf("n%-10s%9s%11s%13s%9sn",
            "yearBuilt","area(sqf)","price","replaceRoof","sqfPrice");
System.out.printf("n%-10d%9.1f$%11.2f%13s$%8.2fn",
            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位数字,将平方英尺价格指定为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)

将输出CCD_ 2。

如果能够在java中的printf语句中使用"$"符号,那就太好了,但我们必须在java中使用特殊的类。好消息是在api中有这样的可用性。

从以下内容开始。

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

希望能有所帮助。

最新更新