Adding up fractions in PHP

Posted by Gamemorize on Stack Overflow See other posts from Stack Overflow or by Gamemorize
Published on 2013-10-21T08:16:44Z Indexed on 2013/10/21 9:54 UTC
Read the original article Hit count: 216

Filed under:
|
|

I would like to create a loop that keeps adding a set fraction, here in my example 1/3, and which later I can check against for matches with integer values.

Obviously when php adds 1/3 + 1/3 + 1/3 the result is 0.9999999, so i thought I could use the occasional round to help me, but this isn't working either.

The idea that I had would be that .333 + .333 becomes .666 and that if rounded that would become .667, then + .333 and the result is 1. However round only seems to work, for me, if the number of digits actually decreases. so round (0.666, 3) remains 0.666

<?php
    $denom = 3;
    $frac = 1/$denom;
    $frac = round($frac,3);

    $value = 0;
    $max =24;
    for($f = 1; $f <= $max; $f++){
    echo "old value is now at ".$value.".<br/>";
    $value = $value+$frac;
    echo "value is now at ".$value.".<br/>";
    $value = round($value,3);
    echo "rounded value is now at ".$value.".<br/>";
    $valueArray[$f] = $value;
    //and here for ease of testing....
    if (($value==1)OR ($value==2)OR ($value==3)OR ($value==4)OR ($value==5)OR ($value==6)OR ($value==7)OR ($value==8)){
         echo "match!<br/>";
    }else{
        echo "no match!<br/>";
    }
    }


?>

Am I going about this in a totally stupid way?

Accuracy when the value is not an integer is not needed, just that it can == with integers.

© Stack Overflow or respective owner

Related posts about php

Related posts about round