0

In PHP, I need to write a function that takes a string and returns its conversion to a float whenever possible, otherwise just returns the input string.

I thought this function would work. Obviously the comparison is wrong, but I don't understand why.

function toNumber ($input) {
    $num = floatval($input); // Returns O for a string
    if ($num == $input) { // Not the right comparison?
        return $num;
    } else {
        return $input;
    }
}

echo(gettype(toNumber("1"))); // double
echo(gettype(toNumber("3.14159"))); // double
echo(gettype(toNumber("Coco"))); // double (expected: string)

3 Answers3

5
function toNumber($input) {
    return is_numeric($input) ? (float)$input : $input;
}
deceze
  • 510,633
  • 85
  • 743
  • 889
1

try if($num){return $num;}else{return $input}, this will work fine, it will only jump to else statement part, when $num = 0

0

Well the fastest thing would be checking if $num == 0 rather than $num == $input, if I understand this correctly.

Jurijs Kastanovs
  • 685
  • 1
  • 15
  • 35