How to do decimal number validation in PHP?
:)
(The decimal point is optional) it should accept ... 0 , 1 , 2 , 0.123 , 0.2 , 12.34 etc.
How to do decimal number validation in PHP?
:)
(The decimal point is optional) it should accept ... 0 , 1 , 2 , 0.123 , 0.2 , 12.34 etc.
if (is_integer($num) || is_float($num)) {
// OK :)
} else {
// Not so good... :/
}
suggested is_float/is_numeric won't work, because is_float doesn't accept request parameters (which are strings) and is_numeric will accept something like "+.1e0" which is not what you want. The reliable way is to use regular expression for validation, for example
$is_decimal = preg_match('/^\d+(\.\d+)?$/', $some_string);
the expression may vary depending on your needs. For example, the above will also accept "000.00" or "111111111111111".
Answers for english locale have already been posted. The NumberFormatter::parse() takes care of other locales, if you need such behaviour:
$formatter = new NumberFormatter('de-DE', NumberFormatter::PATTERN_DECIMAL);
if ($formatter->parse($value) !== false) {
# A correct numeric value in german locale, like '12.345,00001'
}