Home » Php » php – Why does the `FILTER_VALIDATE_NUMBER_FLOAT` constant drop the decimal place character?

php – Why does the `FILTER_VALIDATE_NUMBER_FLOAT` constant drop the decimal place character?

Posted by: admin April 23, 2020 Leave a comment

Questions:
$quantity = filter_input(INPUT_GET, 'quantity', FILTER_SANITIZE_NUMBER_FLOAT);

Input: 100.25

Output: 10025

How can I preserve the . character?

How to&Answers:

Try this…

$quantity = filter_input(
              INPUT_GET, 
              'quantity', 
              FILTER_SANITIZE_NUMBER_FLOAT, 
              FILTER_FLAG_ALLOW_FRACTION
            );

CodePad.

Answer:

Reading the documentation http://www.php.net/manual/en/filter.filters.sanitize.php shows that FILTER_SANITIZE_NUMBER_FLOAT has the following effect:

Remove all characters except digits, +- and optionally .,eE.

Turning this rather poorly formed sentence around:

This removes all characters from the input except digits (0-9). With optional flags, it is possible to also allow the characters . (dot) , (comma) e (exponent) and E (exponent)

So, your code example isn’t multiplying, but it is stripping the decimal point.

Solution:

You need to set the option FILTER_FLAG_ALLOW_FRACTION in your function call to allow the decimal point:

$quantity = filter_input(INPUT_GET, 'quantity', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

Answer:

You want:

$quantity = filter_var(100.25, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

print_r($quantity);

http://codepad.org/ch66qJru

Woops.. You’ll want to still use filter_input as you currently have as well as the same first two args. I ended up using filter_var so I could test it in codepad and forgot to change it back 😛

Answer:

Alternatively, use FILTER_VALIDATE_FLOAT, with a quick feedback note if it doesn’t match:

    $quantity = (filter_input(INPUT_GET, 'quantity', FILTER_VALIDATE_FLOAT))
                ?filter_input(INPUT_GET, 'quantity', FILTER_VALIDATE_FLOAT):
                "Invalid Decimal Number";

    print_r($quantity);