Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string format to add dollar sign and commas to my numbers

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. :)

like image 969
Tessa Avatar asked Sep 11 '25 21:09

Tessa


2 Answers

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

DecimalFormat dFormat = new DecimalFormat("####,###,###.##");
System.out.println("$" + dFormat.format(income));
like image 57
Bruno Caceiro Avatar answered Sep 13 '25 10:09

Bruno Caceiro


Solution with String.format only:

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

it will print Income $50,000.00

like image 43
Ruslan Avatar answered Sep 13 '25 10:09

Ruslan