0

I'm looking for a PHP version for the Javascript modulus (%) operation. I need to get this for some mapping algorithms I'm trying to port to PHP. When I use PHP's bcmod, my results are off some.

Here's what I have so far.

public static function mod($operand_str, $modulus_res)
{
    $arg_arr = array();
    $arg_arr = func_get_args();

    $operand_str = strval($operand_str);
    $modulus_res = strval($modulus_res);

    $retain_scale_bool = (!isset($arg_arr[2]) || $arg_arr[2] == '') ? false: $arg_arr[2];

    //get decimal
    $decimal_arr = array();
    $decimal_arr = explode('.', $operand_str);

    switch(true)
    {
        case ($retain_scale_bool == true):
            $modulus_new_res = bcmod($operand_str, $modulus_res);
            $modulus_new_res = $modulus_new_res.'.'.$decimal_arr[1];
        break;

        default:
            $modulus_new_res = bcmod($operand_str, $modulus_res);
    }

    return $modulus_new_res;
}

Just as an example. Here are the results I get when I do 3.1432444 % 3: With Javascript: 0.14324439999999994 With PHP: 0 With My Function: 0.1432444

I want to get the Javascript result with my function.

Can you help adjust my script. I'm no math wiz so I'm not going to be able to take this to the first principles of the modulus operation.

Thanks.

ObiHill
  • 11,448
  • 20
  • 86
  • 135

1 Answers1

5

You can use fmod(), which works with floats:

fmod(3.1432444, 3);
István Ujj-Mészáros
  • 3,228
  • 1
  • 27
  • 46
  • my function already gives me the same result as fmod(). I want to get the result that I mentioned is returned by Javascript?! – ObiHill Dec 18 '10 at 23:03
  • @Chuck: I don't understand how the modulus in JS for `3.1432444 % 3` would give you 0.14324439999999994... Where is the 9999999994 bit coming from? If anything, it's the JS version that is giving you the wrong result, or the actual left operand is not 3.1432444. – netcoder Dec 18 '10 at 23:19
  • @Netcoder: That's what I got. Maybe you can try it out yourself. Is the result wrong then?! – ObiHill Dec 18 '10 at 23:27
  • @Chuck See [this](http://stackoverflow.com/questions/3966484/floating-point-numbers-and-javascript-modulus-operator) question and the answers. – István Ujj-Mészáros Dec 18 '10 at 23:29
  • @Netcoder: Thanks. I guess I'll stick with my function since javascript has errors. – ObiHill Dec 19 '10 at 00:06