Question

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.

Was it helpful?

Solution

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

fmod(3.1432444, 3);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top