3

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.

The Humble Rat
  • 4,586
  • 6
  • 39
  • 73

1 Answers1

5

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.

Daan
  • 12,099
  • 6
  • 34
  • 51
  • 1
    @yaa110 That is because 0.29 does not exist as a float number: `printf('%.20f',0.29)` shows you: `0.28999999999999998002` – Daan May 19 '15 at 14:40
  • @Daan please see the result from the following: `number_format(floor(-0.9999999999*100)/100, 2);` this is giving me -1. It works well for positive numbers though. – The Humble Rat May 19 '15 at 14:45
  • @TheHumbleRat Works for negative numbers aswell you just need to change `floor` to `ceil` function. – Daan May 19 '15 at 14:47
  • @Daan so it does. Good man. Many thanks for this. One for the snippets. – The Humble Rat May 19 '15 at 14:53