doudu9148 2010-12-18 22:25
浏览 49
已采纳

PHP版本的Javascript Modulus操作

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.

  • 写回答

1条回答 默认 最新

  • douyue1926 2010-12-18 22:29
    关注

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

    fmod(3.1432444, 3);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计