2

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?

3
  • @Devon read the question again... He's not considering the 1,000.00 case just 1000.00 Commented Nov 8, 2016 at 13:09
  • @Jackowski, you're right, I skimmed through the first time. Commented Nov 8, 2016 at 13:16
  • The string replacement is unnecessary, floatval will already treat , or . as the decimal separator. Commented Nov 8, 2016 at 13:19

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for considering the precision, which I did not. I'll remove the floatval() because I'll do arithmetic operations with that number. Also, +1 for the link and the mention of the BC Math extension.

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.