jefffan24
jefffan24

Reputation: 1326

problems with number_format and negative numbers

Right now I'm storing numbers as a double(11,3) in my database. Some of the numbers can be larger negatives. The one I'm playing with right now is -3000.000

When I use number_format on just 3000.000 it returns 3,000 When I use number_format on -3000.000 it returns -3

Any ideas why this is happening and what I can do to fix it? I'm kind of at a loss right now as to why this is happening.

Thanks,

Jeff

EDIT: I got it to work with the following code:

$number = abs($row['Amount']) * -1; $final = number_format($number,2);

Now why that would work and not:

$final = number_format($row['Amount'],2); 

I haven't got a clue, but at least I found a solution, thanks for the help :)

Upvotes: 2

Views: 14176

Answers (4)

Shameer
Shameer

Reputation: 3066

try this:

if($input<0){
  $number = abs($input);
  $result = number_format($number) * -1;
}else {
  $result = number_format($input);
}

Upvotes: 3

Martin Zeitler
Martin Zeitler

Reputation: 76869

based on Shameer's suggestion, I came to this solution.

trailing zeros on negative values will be returned (probably as expected):

if($input < 0){
    return number_format(0-abs($input), 2, ',', '');
}
else {
    return number_format((float)$input, 2, ',', '');
}

Upvotes: 0

salathe
salathe

Reputation: 51970

The result from number_format(-3000.000, 2) is the string, "-3,000.00".

If you don't get that, please update the question with code that reproduces your problem.

Upvotes: 2

adrian7
adrian7

Reputation: 1016

First make sure your number is extracted as -3000 from database. Otherwise previous answers and comments are good.

Upvotes: 1

Related Questions