开发者

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

开发者 https://www.devze.com 2022-12-09 23:48 出处:网络
I\'m currently writing a report in PHP that occasionally has to display negative currency amounts. Said currency amounts are store开发者_StackOverflow社区d in the database like \"-44.00\". Ideally thi

I'm currently writing a report in PHP that occasionally has to display negative currency amounts. Said currency amounts are store开发者_StackOverflow社区d 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.


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

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


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

    else return "$".$amount;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号