DWilliams
DWilliams

Reputation: 451

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

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.

Upvotes: 2

Views: 4986

Answers (3)

Alex
Alex

Reputation: 1

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.

Upvotes: 0

Galen
Galen

Reputation: 30180

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

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

Upvotes: 7

kristofer
kristofer

Reputation: 147

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

    else return "$".$amount;
}

Upvotes: 1

Related Questions