1

floor( 500 * (1.4 / 100) ) gives me 6 and floor( 500 * 1.4 / 100 ) gives me 7

Can anyone help me understand how PHP arithmetic works internally.

6
  • 5
    How can the second example give you 7 ? That doesn't seem possible to me. Commented Oct 15, 2015 at 12:09
  • 4
    You meant floor( 500 * 1.4 / 100) ? Commented Oct 15, 2015 at 12:09
  • 1
    I find it unlikely that 500 * 1.4 * 100 returns anything close to 7. Commented Oct 15, 2015 at 12:10
  • 2
    Is it a typo in the second example (the last *)? It meant to be ` floor( 500 * 1.4 / 100 )`, right? Commented Oct 15, 2015 at 12:10
  • 1
    The second expression returns 70000. Commented Oct 15, 2015 at 12:11

1 Answer 1

6

It works like in any other language. Try for example javascript:

    (500*(1.4 / 100)) // this will give you 6.999999999999999
    (500* 1.4 / 100)  // this will give you 7

The problem is, that PHP has internal setting which tells him about precission with which he displays float numbers. Try doing something like that:

    php > ini_set('precision', 17);
    php > echo ( 500 * (1.4 / 100) );
    6.9999999999999991
    php > echo ( 500 * 1.4 / 100 );
    7
    php >

I assume you've tried the code above without ini_set (using default settings – probably 14 as precision), and it returned you 7 in both results:

    php > echo ( 500 * 1.4 / 100 );
    7
    php > echo ( 500 * (1.4 / 100) );
    7
    php >
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.