dev646
dev646

Reputation: 419

Decimal validation + PHP?

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.

Upvotes: 2

Views: 10776

Answers (4)

soulmerge
soulmerge

Reputation: 75704

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'
}

Upvotes: 5

user187291
user187291

Reputation: 53940

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".

Upvotes: 4

Petah
Petah

Reputation: 46050

Would any of these suit your needs?

Upvotes: 9

fire
fire

Reputation: 21531

Use is_float...

Upvotes: 2

Related Questions