-1

I'm not too much of an expert in Maths but when we try to equate 19.95 / 2.85 in any calculator we get the output as 7.

Trying the same arithmetic equation in PHP:

$val = 19.95 / 2.85;
echo $val; // 7
echo floor($val); // 6

Trying the same arithmetic equation in JavaScript:

var val = 19.95 / 2.85;
console.log(val); // 6.999999999999999
console.log(Math.floor(val)); // 6

How can I make sure that when i use floor() in PHP that the output I get from the above arithmetic equation equals 7?

Eric P Pereira
  • 450
  • 1
  • 7
  • 18
  • This is a known issue in JavaScript: https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Emil S. Jørgensen Jul 10 '17 at 09:51
  • 3
    Possible duplicate of [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – Companjo Jul 10 '17 at 09:55
  • ok... but what's wrong with the PHP code then? – Eric P Pereira Jul 10 '17 at 09:59
  • @EricPPereira Nothing? The result is simply beyond the number of significant decimals that PHP displays, so it rounds up to 7, unless specifically told to round down. – Emil S. Jørgensen Jul 10 '17 at 10:03
  • 1
    @EricPPereira If you want more precision you can try using build in php libraries like BCMath [divide](http://php.net/manual/en/function.bcdiv.php). You can set the default scale with [bcscale](http://php.net/manual/en/function.bcscale.php) – Emil S. Jørgensen Jul 10 '17 at 10:10
  • @EmilS.Jørgenseni Thanks. Will give this a look. – Eric P Pereira Jul 10 '17 at 12:12

1 Answers1

0

You want to get near a value of number ex:

6.5 the near natural integer of is 7

6.4 the near natural integer of is 6

You can to that with javascript with Math.round

var val = 19.95 / 2.85;
console.log(val); // 6.999999999999999
console.log(Math.round(val)); // 7
Mourad Karoudi
  • 348
  • 3
  • 13