PHP Advanced Currency Formatting
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 PH开发者_运维知识库P), but if anyone has any suggestions it would be greatly appreciated.
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.
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
精彩评论