简体   繁体   中英

How do I get the dollar sign to show up beside numerical values in printf method?

Here is my code. I want the dollar sign to print beside each value.

  for(int i = 0; i < enrollment.size(); i++)
    {
        System.out.println(enrollment.get(i).toString());
        System.out.printf("\tTuition: %17.2f \n",enrollment.get(i).calcTuition());
    }

只需将$嵌入格式字符串中即可:

System.out.printf("\tTuition: $%17.2f \n",enrollment.get(i).calcTuition());

One way is to use a NumberFormat currency instance

NumberFormat currencyIntance = NumberFormat.getCurrencyInstance();

double tuition = enrollment.get(i). calcTuition();
System.out.printf("%8s: %9s%n", "Tuition", currencyInstance.format(tuition));

Note, consider avoiding using \\t and \\n inside of your printf. Use format specifier width for \\t and %n in place of \\n .

Try this:

for (int i = 0; i < enrollment.size(); i++) {
    System.out.println(enrollment.get(i).toString());
    System.out.printf("\tTuition: %s \n", String.format("%17.2f", 
                       enrollment.get(i).calcTuition()).trim());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM