PHP : convert String to Float when possible

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)

Upvotes: 0

Views: 197

Answers (3)

Jurijs Nesterovs
Jurijs Nesterovs

Reputation: 255

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

Upvotes: 1

Jurijs Kastanovs
Jurijs Kastanovs

Reputation: 685

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

Upvotes: 0

deceze
deceze

Reputation: 522101

function toNumber($input) {
    return is_numeric($input) ? (float)$input : $input;
}

Upvotes: 5

Related Questions