PHP convert decimal into fraction and back?

前端 未结 14 974
面向向阳花
面向向阳花 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:04

    I made a blog post with a couple solutions for this, the most recent approach I took is: http://www.carlosabundis.com/2014/03/25/converting-decimals-to-fractions-with-php-v2/

        function dec2fracso($dec){
        //Negative number flag.
        $num=$dec;
        if($num<0){
            $neg=true;
        }else{
            $neg=false;
        }
    
        //Extracts 2 strings from input number
        $decarr=explode('.',(string)$dec);
    
        //Checks for divided by zero input.
        if($decarr[1]==0){
            $decarr[1]=1;
            $fraccion[0]=$decarr[0];
            $fraccion[1]=$decarr[1];
            return $fraccion;
        }
    
        //Calculates the divisor before simplification.
        $long=strlen($decarr[1]);
        $div="1";
        for($x=0;$x<$long;$x++){
            $div.="0";
        }
    
        //Gets the greatest common divisor.
        $x=(int)$decarr[1];
        $y=(int)$div;
        $gcd=gmp_strval(gmp_gcd($x,$y));
    
        //Calculates the result and fills the array with the correct sign.
        if($neg){
            $fraccion[0]=((abs($decarr[0])*($y/$gcd))+($x/$gcd))*(-1);
        }else{
            $fraccion[0]=(abs($decarr[0])*($y/$gcd))+($x/$gcd);
        }
        $fraccion[1]=($y/$gcd);
        return $fraccion;
    }
    

提交回复
热议问题