Page 1 of 1

Formatting currency

Posted: Tue May 17, 2005 8:27 am
by Stryks
Hi all.

As usual, I can usually figure my way through the tough stuff, but I seem to always fall short on the simpler things.

Basically, I am looking for the best method of formatting a positive or negative number to appear as either '$5.25' or '- $5.25' (note the space between the minus and the $).

I've looked at money format, but a) I dont want to use setlocale, and b) I cant seem to insert a space as desired. Also looked at sprintf but still to no avail.

Any help here would be hot guys. Cheers.

Posted: Tue May 17, 2005 10:00 am
by Chris Corbyn
Hmmm... cheap and dirty but it should work :P

Code: Select all

function as_currency($num, $symbol) {
    $neg = (abs($num)/$num == -1) ? '- ' : ''; //Notice the space?
    $num = round(abs($num)*10)/10; //2 decimal places
    return $neg.$symbol.$num;
}

//Examples
$amount = -7.52;
echo as_currency($amount, '$'); // - $7.52

$amount = 5.60
echo as_currency($amount, '£') // £5.60

Posted: Tue May 17, 2005 10:19 am
by malcolmboston
Purely for compatability reasons i use number_format asmoney_format is not available on windows machines.

eg usage

Code: Select all

// number_format example
// function is windows and *nix compatable, unlike number_format which is *nix only
$price = 12.34234;
$price = number_format($price, 2);
// output = 12.34

Posted: Tue May 17, 2005 10:31 am
by timvw
with http://be.php.net/manual/en/function.localeconv.php and friends you can localize them :)