views:

439

answers:

3

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.

+6  A: 

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

echo money_format('%(n', '-44.00');
Galen
Upon trying this, it does not add the dollar sign. I've read the documentation for money_format and am still not seeing a way to add the dollar sign.
DWilliams
For clarification, if I call "money_format('%(n', $row['paymentamount'])" when paymentamount is 100, it returns (100.00)
DWilliams
@DWilliams, you can write your own print_money_format($amount) rather easily. PHP is an international language and supports many currencies, it would be sort of silly if it printed a $ by default, even sillier to require another argument (and break existing implementations) by making you specify the currency symbol :)
Tim Post
@tinkertim I think that is what setlocale is for...to set the currency. Says it's supposed to add the $ on php.net, but i cannot get it to do so. Not sure what the deal is.
Galen
+1  A: 
function format_currency($amount) {
    if($amount < 0)
        return "($".$amount.")";

    else return "$".$amount;
}
kristofer
A: 

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.

Alex