Search code examples
phpstringcastingnumeric

Cast string to either int or float


I'm looking for a function that would cast a numeric-string into either integer or float type depending on the content of the string, e.g. "1.23" -> float 1.23, "123" -> int 123.

I know I can use if-s with is_int, is_float and cast to appropriate types - but maybe there is a function that would do it automatically?


Solution

  • No, no function provides the automatic cast. However you can cast with this simple hack (the cast is automatically made by PHP in internal):

    $int = "123"+0;
    $float = "1.23"+0;
    

    for generic number:

    $yourNumberCasted = $yourStringNumber + 0;
    

    With a function:

    function castToNumber($genericStringNumber) { 
        return $genericStringNumber+0; 
    }
    $yourNumberCasted = castToNumber($yourStringNumber);