How do I put a dollar sign when using printf in java?

Michael Peterson :

I want to put a dollar sign in front of the variable price and keep the same format but if I just put it in front of the %36 it will be around 36 characters away.

System.out.printf(" Sale Price %36.2f", price);

Veselin Davidov :

You can do something like:

NumberFormat nf=NumberFormat.getCurrencyInstance();
System.out.printf("  Sale Price %36s", nf.format(price));

Basically use the currency number format and format it as the string you want. Then you use the %36 to print the resulting string at the position you want.

Result:

Sale Price                               $12.30

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306628&siteId=1