TJ Zimmardi
TJ Zimmardi

Reputation: 35

multiple arguments in a printf method

I am writing a code for my Java class that calls for me to create something that looks like a bill/receipt. similar to:

    Item                    quantity                    price            total
    gum                     10                          $1.49            $14.90
    soda                    3                           $1.00            $3.00
    chips                   20                          $1.25            $20.00

I am using the printf(); method. The variables i have declared are

    double gumPrice = 1.49;
    float gumQuantity = 10;
    double gumTotal = 14.90;
    double sodaPrice = 1.00;
    float sodaQuantity = 3;
    double sodaTotal = 3.00;
    double chipsPrice = 1.25;
    float chipsQuantity = 20;
    double chipsTotal = 25.00;

i need to create a few printf(); statements to list the data in that manner.

This is what i have so far for gum, which is giving me an error.

        System.out.printf("%-30s %-10.2f %-10.2f %-5.2f", "Gum",gumQuantity,"$"+gumPrice,"$"+gumTotal);

What is the correct way to put a double in a printf(); while listing multiple arguments in one line?

Upvotes: 0

Views: 8852

Answers (1)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

The original problem was due to incorrect mixing of two methods of formatting Java output, String concatenation and printf formatting. As pointed out in comments, "$"+gumPrice is a String, not a double. It would have to have a %s format, not %f in printf. However, it would be better to pick one way of doing the formatting, and stick with it.

Going with the printf approach, which I think it better in this situation, the output line becomes:

System.out.printf("%-30s %-10.2f $%-10.2f $%-5.2f", "Gum",gumQuantity,gumPrice,gumTotal);

and it prints:

Gum                            10.00      $1.49       $14.90

If you went with the String concatenation approach, you would need to explicitly convert the doubles using a DecimalFormat to force the two decimal places.

The reason to avoid double for money amounts is that many short terminating decimal fractions can only be represented approximately. Your gumPrice is actually 1.4899999999999999911182158029987476766109466552734375, which is very, very slightly different from what you wanted. On the other hand, new BigDecimal("1.49") is exactly 1.49. In some situations, especially if you need to truncate rather than round to nearest, the tiny differences introduced by double can matter, so BigDecimal is safer for currency calculations.

Upvotes: 2

Related Questions