1

Possible Duplicate:
How to check if a number is float or integer?

I have been using a JavaScript function isNaN(value) for identifying whether a number is an integer or a float. But now I am facing another problem that isNaN() is not filtering float. It is accepting it as integer.

Also it must treat 1.0 as an integer

Can someone guide me to find out a way in which I can filter integer values as well?

Community
  • 1
  • 1
OM The Eternity
  • 15,694
  • 44
  • 120
  • 182

3 Answers3

2

In javaScript, there is no difference between decimal and integer, they are both number. One way to diffrentiated is to use regular expression to test the transformed string of the number

var intTest = /^-?(\d+|0)$/;
if(intTest.test(someNumber)) {
   console.log('int');

}

// intTest.test(2);
// true
// intTest.test(2.1);
// false
// intTest.test(0);
// true
// intTest.test(-1);
// true
// intTest.test(-1.2);
// false
steveyang
  • 9,178
  • 8
  • 54
  • 80
1
function is_int(value){ 
  if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
      return true;
  }
  else { 
      return false;
  } 
}

this too:

function isInt(n) {
   return n % 1 == 0;
}

This will work if you want 2.00 to count as an integer.

function is_int(value){ 
   return !isNaN(parseInt(value * 1));
}

Will work if you want strictly of int type.

tekknolagi
  • 10,663
  • 24
  • 75
  • 119
1

You can use regular expression

if(/^-?\d+\.?\d*$/.test(1.23)) {
    // hurray this is a number
}
Maxim Manco
  • 1,954
  • 1
  • 12
  • 19