Is there a PHP function to format a currency amount in accounting format?

拈花ヽ惹草 提交于 2020-01-15 07:11:57

问题


I'm currently writing a report in PHP that occasionally has to display negative currency amounts. Said currency amounts are stored in the database like "-44.00". Ideally this number would be output as "($44.00)" on the report.

I know I can write some semi-complicated function to detect whether the number is negative and manually insert the parenthesis, but I was wondering if there was some handy PHP function that can do this for me before I re-invent the wheel. I've searched around and have not found anything that seems to do this exact task. I know about money_format, but I don't see any way to do the negative/parenthesis part. Keep in mind the code has to function whether the number is negative or positive.


回答1:


http://www.php.net/manual/en/function.money-format.php

echo money_format('%(n', '-44.00');



回答2:


function format_currency($amount) {
    if($amount < 0)
        return "($".$amount.")";

    else return "$".$amount;
}



回答3:


Hmm sort of...but that would still output the minus sign when it is negative. I would change that function to be something like:

function accting_format($amount) {
    if ($amount < 0) return '($' . abs($amount) . ')';
    return '$' . $amount;
}

Notice the abs() around the amount is the parentheses have already been outputted.



来源:https://stackoverflow.com/questions/1625717/is-there-a-php-function-to-format-a-currency-amount-in-accounting-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!