Juan Ligero
Juan Ligero

Reputation: 43

PHP function to safely return a float from string

Let's say I have a form where I ask for a product's price. Basically, I don't consider the case where the user adds the thousands comma, that is: 1,000.00 or 1,000,000.00

I just consider the case where the user inputs 1000.00 or 1000,00 or 1000000.00 but never 1,000.00, or 10,000,000.00 or, even worst, 10.000.000,00

I came up with this function.

function getPrice($price)
{
    if (is_string($price)) {
        if (strpos($price, ",") !== false) {
            $price = str_replace(',', '.', $price);
        }
    }
    return (is_numeric($price)) ? floatval($price) : false;
}

Do you consider safe this function? Can you point improovements?

Upvotes: 2

Views: 560

Answers (1)

krasipenkov
krasipenkov

Reputation: 2029

You function looks OK to me except the last line with floatval.

My main consideration about this approach is that PHP will not represent float correctly thanks to: floatval, casting to float or arithmetic operations with float variables.

For example PHP may convert 10000.00 to 9999,99 depending on the precision set. (you can read more about this here http://php.net/manual/en/language.types.float.php)

If you need this prices for some arithmetic calculations after parsing them to FLOAT (in getPrice function) and you need precision then my advice is to avoid parsing to FLOAT and either:

  • leave them as string and do the calculations with strings
  • use BC MATH extension for more precise math operations in php

Upvotes: 1

Related Questions