The Humble Rat
The Humble Rat

Reputation: 4696

Two Decimal Places without Rounding (Positive and Negative)

I can't believe this has actually come to me asking a question. But I have some decimal values in my database ie 0.9999999, using:

number_format($result['debit'], 2);

number_format($result['debit'], 2,".","");

number_format(floor($result['debit']*pow(10,2))/pow(10,2),2); 

I am continually getting the value 1 back from my original 0.999999.

It doesn't seem to matter what I try, it constantly rounds the number. What can I do to simply get 0.99? I am at the point where I am going to explode (currently I mean the function)

Another note is this will need to work with negative numbers.

Upvotes: 4

Views: 5195

Answers (1)

Daan
Daan

Reputation: 12246

number_format will always round, you can however use below code to make it work:

$number = 0.9999999; 
echo number_format(floor($number*100)/100, 2); //Returns 0.99

Note: use floor() for positive numbers and ceil() for negative numbers.

Upvotes: 5

Related Questions