Formatting currency

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Formatting currency

Post 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.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

Post 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
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

with http://be.php.net/manual/en/function.localeconv.php and friends you can localize them :)
Post Reply