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 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?
  • ¥66 如何制作支付宝扫码跳转到发红包界面