PHP convert decimal into fraction and back?

前端 未结 14 970
面向向阳花
面向向阳花 2020-12-05 07:43

I want the user to be able to type in a fraction like:

 1/2
 2 1/4
 3

And convert it into its corresponding decimal, to be saved in MySQL,

14条回答
  •  清歌不尽
    2020-12-05 08:25

    function dec2frac($f)
    {
        $d = 1
    
        while (fmod($f, 1) != 0.0) {
            $f *= 2;
            $d *= 2;
        }
    
        $n = sprintf('%.0f', $f);
        $d = sprintf('%.0f', $d);
    
        return array($n, $d);
    }
    

    Then $f == $n / $d

    For example:

    print_r(dec2frac(3.1415926));
    

    Outputs:

    Array
    (
        [0] => 3537118815677477  // $n
        [1] => 1125899906842624  // $d
    )
    

提交回复
热议问题