How do I get a float value when dividing two integers? (PHP)

后端 未结 4 765
感情败类
感情败类 2020-12-11 00:43

Hi I am trying to divide two integers ex: 12/13 but I always get a whole integer 1 not a decimal number.

I tried type casting the values to float before hand with no

4条回答
  •  囚心锁ツ
    2020-12-11 01:13

    Under normal circumstances your code should return the floating value 0.923076...

    The reason you get a rounded integer might be because you have your ini setting for "precision" set to 0, to fix this either edit your php.ini or use ini_set("precision", 3); in your code before the calculation.

    Another way to workaround this is to use BCmath:

    echo $value=bcdiv($a, $b, 3);
    

    And yet another way without using any extension is to use a little math trick by multiplying the value you want to divide by 1000 to get 3 decimals.
    This way you'll divide 12000 by 13 and the whole part will be 923, then since you multiplied by 1e3 insert a comma/dot before the last most 3 places.

    function divideFloat($a, $b, $precision=3) {
        $a*=pow(10, $precision);
        $result=(int)($a / $b);
        if (strlen($result)==$precision) return '0.' . $result;
        else return preg_replace('/(\d{' . $precision . '})$/', '.\1', $result);
    }
    

    echo divideFloat($a, $b); // 0.923

提交回复
热议问题