WHY AND HOW this happen?!?!?!?

Discussion in 'PHP' started by HamedAl-Salmi, Nov 17, 2007.

  1. #1
    Try copying this code and past it to a new php file and see the result

    $total=1267.085;
    $rrr=85.100;
    $ppp=1181.985;
    $mmm=$total-$ppp-$rrr;
    echo"The value of mmm is $mmm .";
    PHP:
    The value of $mmm is 1.4210854715202E-013 :confused: WHY AND HOW??????? It must be zero

    IF i change the forumal to $mmm=$total-$rrr-$ppp; it works correctly and the result will be zero

    Any idea what is the problem here?
     
    HamedAl-Salmi, Nov 17, 2007 IP
  2. drunnells

    drunnells Peon

    Messages:
    79
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I wonder if this is the issue with floating point precision, see:
    http://us.php.net/manual/en/language.types.float.php

     
    drunnells, Nov 17, 2007 IP
  3. kemus

    kemus Guest

    Messages:
    487
    Likes Received:
    19
    Best Answers:
    0
    Trophy Points:
    0
    #3
    1.4210854715202E-013 = 0.00000000000014210854715202
    That is not very far off from 0. The problem is that computers work in binary, and just like 1/7 is impossible to write in decimal form in base 10 (decimal), so are some numbers in binary.

    Do you really need to be accurate to the ten-trillionth digit? Try just rounding it to 3 decimals with round()
     
    kemus, Nov 17, 2007 IP
  4. e96

    e96 Active Member

    Messages:
    299
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    80
    #4
    yes, arbitrary precision is the way to go. Here's how you could use the bcmath class to do your calculations using bcsub(). Note the third parameter '3' rounds the number to the third decimal place.

    $total=1267.085;
    $rrr=85.100;
    $ppp=1181.985;
    $a = bcsub($total,$ppp,3);
    
    $mmm=$total-$ppp-$rrr;
    $mm2 = bcsub($a,$ppp,3);
    echo"The value of mmm is $mmm .";
    echo "<br /> $mm2  is  more accurate subtraction";
    Code (markup):
     
    e96, Nov 17, 2007 IP
  5. HamedAl-Salmi

    HamedAl-Salmi Peon

    Messages:
    7
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    thanks a lot for replaying ...
     
    HamedAl-Salmi, Nov 17, 2007 IP