0

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.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Manish Prajapati
  • 1,583
  • 2
  • 13
  • 21
  • 1
    What? Could you clarify what you mean? Also please include a example and your expected output, also, have you tried something? – Epodax Sep 15 '15 at 11:56
  • 1
    [ctype_digit](http://www.php.net/manual/en/function.ctype-digit.php) – Mark Baker Sep 15 '15 at 11:57
  • *i want* Stack Overflow is not a free code writing service. Show us where you are stuck and we are happy to help – Rizier123 Sep 15 '15 at 11:58

3 Answers3

1

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.

Community
  • 1
  • 1
NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
  • `strpos()` won't work with an int, so you need to cast the ID to a string if you are gonna use `strpos()`. The variable might be a real int or float. – Timmetje Sep 15 '15 at 12:13
  • $a should be a string here. i have used `===` to compare types as well. – NeverHopeless Sep 15 '15 at 12:18
  • But we don't know if `$a` is a string, it could be anything. So you might want to add some code to make sure it is, or add checks if it's an integer or float. – Timmetje Sep 15 '15 at 12:20
1

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.

Timmetje
  • 7,641
  • 18
  • 36
0

Use is_float() function to find invalid numbers

chris85
  • 23,846
  • 7
  • 34
  • 51
Samuel Kelemen
  • 176
  • 1
  • 1
  • 8