3

I'm relatively new to Java, and I have a line of code I'm struggling with:

System.out.println(String.format("%-14s%10.2f","Income",income));

I would like to add a $ and commas to the income, but whenever I try to add it in the line, I get errors or the $ shows up in the wrong spot.

So currently it prints:

Income      50000.00

but I would like it to print:

Income     $50,000.00

If there is a way to add these additions while keeping 'Income' and the digits nicely spaced apart, that'd be preferred. :)

Tessa
  • 49
  • 1
  • 7

3 Answers3

2

If you wish to display $ amount in US number format than try:

DecimalFormat dFormat = new DecimalFormat("####,###,###.##");
System.out.println("$" + dFormat.format(income));
Bruno Caceiro
  • 7,035
  • 1
  • 26
  • 45
2

Solution with String.format only:

System.out.println(String.format("%-14s$%,.2f","Income",50000.));

it will print Income $50,000.00

Ruslan
  • 6,090
  • 1
  • 21
  • 36
1

You should use decimal format and format the number.

DecimalFormat formatter = new DecimalFormat("#,###,###");
String yourFormattedString = formatter.format(100000);
System.out.println("$" + yourFormattedString);

The result will be

-> 1,000,000 for 1000000         
-> 10,000 for 10000         
-> 1,000 for 1000
Asad Ali
  • 309
  • 3
  • 14
  • 2
    Why has this been downvoted? The answer here is no different from the one above – Frontear Jan 16 '19 at 19:08
  • Question *specifically* asked for formatting with $ sign, and this answer doesn't do that. – Andreas Jan 16 '19 at 19:14
  • 1
    @Andreas Seems to me that the line `System.out.println("$" + yourFormattedString);` DOES use the dollar sign. – FredK Jan 16 '19 at 19:26
  • @FredK You mean the `print` statement that was added to the answer *after* I left the comment? --- Also note that I'm not the downvoter, just my take on why a downvote could have been given. – Andreas Jan 16 '19 at 21:36
  • Better yet: `NumberFormat.getCurrencyInstance(Locale.US)` – Andreas Jan 16 '19 at 21:36