views:

3118

answers:

4

How do you convert a number to a string showing dollars and cents?

eg:
123.45    => '$123.45'
123.456   => '$123.46'
123       => '$123.00'
.13       => '$0.13'
.1        => '$0.10'
0         => '$0.00'
+1  A: 

In PHP and C++ you can use the printf() function

printf("$%01.2f", $money);
nickf
The built in PHP functions are really handy.
Darryl Hein
+7  A: 

PHP also has money_format().

Here's an example:

echo money_format('$%i', 3.4); // echos '$3.40'

This function actually has tons of options, go to the documentation I linked to to see them.

yjerem
From the doco:Note: The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.
too much php
A: 

In C# use the currency format specifier :C

string.Format("{0:C}", someValue);

Tim Jarvis
heh - i just changed the question to be PHP-specific, but thanks for the answer anyway.
nickf
+5  A: 

If you just want something simple:

'$' . number_format($money, 2);

number_format()

Darryl Hein
be aware that this will add a comma (or the equivalent in your locale) after each grouping of three digits. this might be desired, but could be very confusing if you weren't expecting it.
nickf