Kblo55
Kblo55

Reputation: 65

printf formatting in Java

Here is my code:

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());

And here is the output I'm getting:

    yearBuilt area(sqf)      price  replaceRoof sqfPrice


    1996         2395.0$  195000.00         true$   81.42

This is the output I want:

    yearBuilt area(sqf)       price  replaceRoof sqfPrice


    1996         2395.0  $195000.00         true   $81.42

I tried using DecimalFormat but for some reason it didn't seem to work correctly when using it inside printf, when it worked normally in another area of my program. Any ideas on how to fix this?

Upvotes: 3

Views: 332

Answers (2)

Nirmal
Nirmal

Reputation: 1259

It would be nice to be able to use the "$" sign with printf statements in java but we have to use the special class for that in java. The good news is that there are such available in the api.

Start with something like below.

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());

Hope that helps.

Upvotes: 0

Jean-François Savard
Jean-François Savard

Reputation: 21004

The problem is that you specify the price to be 11 digits fixed before the decimal, and sqfPrice to be 8 digits which cause the padding spaces.

If you decorticate your print statement :

System.out.printf("$%11.2f", 195000.0f);//print $  195000,0
System.out.printf("$%8.2f", 81.42f);//print $   81,42

You might want to use NumberFormat instead

NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);

Assuming you gave US locale,

currencyFormatter.format(195000)

would output $195,000.00.

Upvotes: 1

Related Questions