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.
Formatting currency
Moderator: General Moderators
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Hmmm... cheap and dirty but it should work 
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
Purely for compatability reasons i use number_format asmoney_format is not available on windows machines.
eg usage
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.34with http://be.php.net/manual/en/function.localeconv.php and friends you can localize them 