Search code examples
phpcastingfloating-pointtype-conversiondecimal

Cast a numeric string as float type data


What is the PHP command that does something similar to intval(), but for decimals?

Eg. I have string "33.66" and I want to convert it to decimal value before sending it to MSSQL.


Solution

  • How about floatval()?

    $f = floatval("33.66");
    

    You can shave a few nanoseconds off of type conversions by using casting instead of a function call. But this is in the realm of micro-optimization, so don't worry about it unless you do millions of these operations per second.

    $f = (float) "33.66";
    

    I also recommend learning how to use sscanf() because sometimes it's the most convenient solution.

    list($f) = sscanf("33.66", "%f");