4

I am trying to format a string whereby the '$' stick close to the price.

For example:

Oranges     3     $3.00     $9.00

But what I currently have:

Oranges     3 $    3.00 $    9.00

This is my code: (Note: "price" and "total" are double datatype)

System.out.printf("%-25s %10s $%10s $%10s", item, quantity, price, total);

I want to have a gap in between every output but I can't find a way to get the result that I wanted. Is there any ways to solve this?

1

3 Answers 3

1

try

System.out.printf("%-25s %10s %10s %10s", item, quantity, "$" + price, "$" + total);

output

Oranges                            3       $3.0       $9.0

or, best of all, use a formatter method

    String format(double d) {
        return String.format("$%.2f", d);
    }
...
    System.out.printf("%-25s %10s %10s %10s", item, quantity, format(price), format(total));

output

Oranges                            3      $3.00      $9.00
Sign up to request clarification or add additional context in comments.

Comments

0

Take out the 10 space padding on the price and the total.

System.out.printf("%-25s %10s $%s $%s", item, quantity, price, total);

Comments

0

Could you just convert them to a String for output? The Double type can have the toString() method called on it, as per this link:

http://www.java2s.com/Code/Java/Language-Basics/Convertdoubletostring.htm

And then you can just output a dollar symbol at the top of each string (you could even loop through all the strings if you load them into an array, and add a dollar symbol to all of them).

This might not be the best option, but I'm sure it'll work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.