3

In my program I print out a table, one of the columns has money listed. I want to print out the money values neatly and right justified, like below:

  $9.00
  $8.00
 $19.20
$200.90

I can right justify the numbers like so

while(condition)
{
   printf("$%5.2f\n", number);
}

But obviously with this method the $ isn't positioned where I want it, and I get an output more like:

$    9.00
$    8.00
$   19.20
$  200.90

Can I get the formatting I want simply with printf?

user1783150
  • 281
  • 2
  • 6
  • 13

2 Answers2

3

You can do it with auxiliary string:

while(condition)
{
   char str[10] = {};
   sprintf(str, "$%.2f", number);
   printf("%8s\n", str);
}
Ofir Luzon
  • 10,635
  • 3
  • 41
  • 52
2

It is very difficult to achieve this by using simply printf. For currency-sensitive formatting you should use the strfmon() function.
For more detailed explanation read this answer given by Jonathan Leffler.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264