In PHP development, ensuring the validity and safety of data—especially user input—is crucial. PHP offers built-in filters to help with this, and one of the most useful for numeric data is FILTER_SANITIZE_NUMBER_FLOAT. This constant is used to strip a string of all characters except digits, plus/minus signs, and optionally a decimal point. It is commonly used for pre-processing form data or handling numeric values from APIs.
The typical usage of FILTER_SANITIZE_NUMBER_FLOAT looks like this:
$sanitized_number = filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT, $filter_options);
Parameter explanation:
$number = "5a.1b4 2c2";
$sanitized_number = filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT);
echo $sanitized_number;
Output:
<span class="fun">5.1422</span>
In this example, all non-numeric characters are removed, leaving a properly formatted float.
Using filter flags, we can fine-tune how the number is cleaned:
$number = "8.9000";
$sanitized_number = filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_STRIP_TAIL);
echo $sanitized_number;
Output:
<span class="fun">8.9</span>
Here, FILTER_FLAG_STRIP_TAIL removes unnecessary trailing zeroes from the decimal.
In international applications, the decimal separator might be a comma instead of a dot. You can specify this in the options:
$number = "8,9";
$filter_options = array("decimal" => ",");
$sanitized_number = filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT, array("options" => $filter_options));
echo $sanitized_number;
Output:
<span class="fun">8.9</span>
By specifying "decimal" => ",", the filter correctly interprets the comma as a decimal point.
FILTER_SANITIZE_NUMBER_FLOAT is a powerful and flexible tool in PHP for sanitizing numeric input. It ensures that only valid numeric characters remain, and with the use of additional flags and options, developers can tailor the behavior to fit various needs. It's especially useful when building secure, well-structured applications where strict data formatting is required.