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.
Would any of these suit your needs?
- is_float()
- is_numeric()
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'
}
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".
Use is_float...
精彩评论