1

I have a float: 9.174599999999995

Which when I run number_format(9.174599999999995, 2) I am getting 9.17. I believe I should be getting 9.18 as the 4 rounds up to 5 and then the 7 rounds to 8. Is this not right? How can I achieve the desired result of 9.18?

Dogday
  • 175
  • 2
  • 9

4 Answers4

0

This is because number_format doesn't round : http://php.net/manual/en/function.number-format.php

Take a look at round function : http://php.net/manual/fr/function.round.php

Dan Chaltiel
  • 7,811
  • 5
  • 47
  • 92
0

Well, you assume wrong, the correct answer is 9.17, because the rounding is made based on just one digit after the rounding point. Basically when you round 9.174599999999995 with 2 decimals, you round it based on 4, which is smaller than 5, so the number is rounded to 9.17

sticksu
  • 3,660
  • 3
  • 23
  • 41
0

due to case you can use php round. Examples:

$n=3.18925

$round=round($round, 1);

it will be displayed 3.2

$round=round($round, 2);

it will be displayed 3.19

Rashad
  • 1,344
  • 2
  • 17
  • 33
0

For your number,

$number = 9.17499999999995 ;
echo $english_format_number = number_format($number, 2, '.', '');
9.17

$number = 9.17599999999995 ;
echo $english_format_number = number_format($number, 2, '.', '');
9.18

and by using number_format for 2 times you can achieve desire result

$number = 9.17499999999995 ;
echo $number = number_format($number, 3, '.', '');
echo "<br>";
echo $english_format_number = number_format($number, 2, '.', '');  

RESULTS    
    9.175
    9.18
Rishabh
  • 546
  • 5
  • 8