-1

I need to display a fraction in PHP. For that I wrote:

$a = 3;

$b = 2;

$c = "$a/$b";

echo $c; // this displays 3/2 but on the other hand I want to multiply $c by an integer;

echo $c * 2; // this shows me an error

this is what shows me : ( ! ) Notice: A non well formed numeric value encountered

Can someone help me please?

marwa
  • 19
  • 2

1 Answers1

0
  • remove the double quote around operations ($a/$b) because it mean it is a string not an integer or float

    $a = 3;
    $b = 2;
    $c = $a/$b; 
    echo $c * 2;
    
  • to display fraction it is another story

maybe look at this PHP convert decimal into fraction and back?

  • or use this function

    function decimalToFraction($decimal){
    
        if ($decimal < 0 || !is_numeric($decimal)) {
            // Negative digits need to be passed in as positive numbers
            // and prefixed as negative once the response is imploded.
            return false;
        }
        if ($decimal == 0) {
            return [0, 0];
        }
    
        $tolerance = 1.e-4;
    
        $numerator = 1;
        $h2 = 0;
        $denominator = 0;
        $k2 = 1;
        $b = 1 / $decimal;
        do {
            $b = 1 / $b;
            $a = floor($b);
            $aux = $numerator;
            $numerator = $a * $numerator + $h2;
            $h2 = $aux;
            $aux = $denominator;
            $denominator = $a * $denominator + $k2;
            $k2 = $aux;
            $b = $b - $a;
        } while (abs($decimal - $numerator / $denominator) > $decimal * $tolerance);
    
        return [
            $numerator,
            $denominator
        ];
    }
    

source https://www.designedbyaturtle.co.uk/converting-a-decimal-to-a-fraction-in-php/

AlainIb
  • 4,544
  • 4
  • 38
  • 64