For example if I had:
1.2
1.65
5
9.5
125
Valid numbers would be 5
and 125
.
Invalid numbers : 1.2
, 1.65
, 9.5
I am stuck in checking whether a number has a decimal or not.
I tried is_numeric
but it accepted numbers with a decimal.
For example if I had:
1.2
1.65
5
9.5
125
Valid numbers would be 5
and 125
.
Invalid numbers : 1.2
, 1.65
, 9.5
I am stuck in checking whether a number has a decimal or not.
I tried is_numeric
but it accepted numbers with a decimal.
A possibility is to try using strpos
:
if (strpos($a,'.') === false) { // or comma can be included as well
echo 'Valid';
}
or try it using regex:
if (preg_match('/^\d+$/',$a))
echo 'Valid';
Examples taken from here.
If you are sure the number variable is not a string you can use is_int()
to check whether it is valid or is_float()
to check whether it is invalid.
But if you handle forms for example the variable is often a string which makes it harder and this is an easy solution which works on strings, integers and floats:
if (is_numeric($number)) {
//if we already know $number is numeric...
if ((int) $number == $number) {
//is an integer!!
}
}
It's also faster than regex and string methods.