views:

241

answers:

5

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.

+5  A: 

Would any of these suit your needs?

Petah
xcellent ... thanx a lot... such a fn. was available? i was googling like anything... !
dev646
@dev646: Make sure you read the comments on the is_float function page. They are really helpful
AntonioCS
A: 
if (is_integer($num) || is_float($num)) {
// OK :)
} else {
// Not so good... :/
}
TiuTalk
Doesn't work if the value is a string "0.123".
Tatu Ulmanen
@Tatu Ulmanen - Use the correct data type when you want to trust in your validation
TiuTalk
@TiuTalk, but take in account that you cannot affect the data type when you get your variables through a $_POST request, for example.
Tatu Ulmanen
@Tatu Ulmanen - But you cant' just rely on the $_POST or $_GET data.. You need some modifications, sanitizations and THEN validations. That's what I think
TiuTalk
thanx brother...
dev646
+1  A: 

Use is_float...

fire
thanx....... :)
dev646
A: 

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

stereofrog
-1 `if ((float)$a==$a)` would be acceptable, but not regular expressions
soulmerge
thanx for your effort ... :)
dev646
@soulmerge: you didn't read my post correctly, i'm afraid. Both functions would accept "+.1e0" which is hardly "decimal"
stereofrog
A: 

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