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)
1

3 Answers 3

5
function toNumber($input) {
    return is_numeric($input) ? (float)$input : $input;
}
Sign up to request clarification or add additional context in comments.

4 Comments

is_numeric? Well.. hem... OK.
Makes sense if you think about it, no? ;-3
That's the trouble with PHP. Too many built-in functions with imprectidable names (well, not this one)!
Mmm, fair enough. It's worth perusing the list of basic functions once or twice though, like all string functions and all number functions. There's aren't that many... :)
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.