Java formatting

I am trying to format a string where the $ binding is close to the price.

For instance:

Oranges 3 $3.00 $9.00 

But I currently have:

 Oranges 3 $ 3.00 $ 9.00 

This is my code: (Note: "price" and "general" are dual data types)

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

I want to have a gap between each output, but I cannot find a way to get the result that I wanted. Are there any ways to solve this problem?

+4
source share
3 answers

to try

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

Output

 Oranges 3 $3.0 $9.0 

or, best of all, use the formatting 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 
+1
source

Pull out 10 spaces for price and amount.

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

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

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

And then you can just print the dollar symbol at the top of each line (you can even skip all the lines if you load them into an array and add a dollar symbol to all of them).

This may not be the best option, but I'm sure it will work.

0
source

All Articles