0

I was wondering if there is a simple method in PHP to format currency correctly for the following tasks:

If a value is: 4.37 then the output will be $4.37

If a value is: 4.00 then the output will be $4

If a value is: 4.3 or 4.30 then the output will be $4.30

If a value is 0.37 then the output will be 37¢

I'm sure this is quite complicated to do (I'm a beginner in PHP), but if anyone has any suggestions it would be greatly appreciated.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
TronCraze
  • 295
  • 1
  • 6
  • 14

2 Answers2

1
function format_currency($val) {
    if ($val < 1) return intval(round($val * 100)) . '¢';
    if (fmod($val, 1.0) == 0) return '$' . intval($val);
    return '$' . intval($val) . '.' . intval(round((fmod($val,1))*100));
}

// Call it like this
$val = 1.2;
echo 'Your total: ' . format_currency($val);

Although this function will work, it's generally a bad idea to encode dollar amounts in a float.

Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469
  • Hi phihag, your function looks like it could work but I've tried using the code and nothing appears to display onscreen. I tried this: ` – TronCraze Feb 19 '11 at 20:30
  • @TronCraze You have to actually call it. Add echo format_currency($val); . I updated the answer. – phihag Feb 19 '11 at 22:50
  • 2
    your last line could be made simpler using the built in php function `setlocale(LC_MONETARY, 'en_US'); money_format('$%!n', $val)` doing exactly the same job. – Chris Pennycuick Feb 20 '11 at 01:57
0

I know this might be a bit of an overkill but take a look at Zend_Currency, it will take care of many different types of currency for this, it's also simple to use. Do note that you don't have to use the whole framework, just the currency class and the file it requires

http://framework.zend.com/manual/en/zend.currency.html

allenskd
  • 1,795
  • 2
  • 21
  • 33