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?

5
  • 1
    A decimal is a number. Perhaps you mean integer?
    – tekknolagi
    Commented Nov 17, 2011 at 10:09
  • 1
    +1 to u @tekknolagi Yes I do mean integer Commented Nov 17, 2011 at 10:10
  • @OMTheEternity unfortunately comment upvotes get no rep
    – tekknolagi
    Commented Nov 17, 2011 at 10:11
  • Maybe this will help: stackoverflow.com/questions/3885817/…
    – fredrik
    Commented Nov 17, 2011 at 10:13
  • @OMTheEternity see my answer :) enjoy!
    – tekknolagi
    Commented Nov 17, 2011 at 10:14

3 Answers 3

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

3
  • I say of int type, but there is only number in JS. You know what I mean.
    – tekknolagi
    Commented Nov 17, 2011 at 10:16
  • The Last Solutions accepts the alphabets.. I need only integers to passthrough Commented Nov 17, 2011 at 10:27
  • @OMTheEternity the last solution will not accept strings.
    – tekknolagi
    Commented Nov 18, 2011 at 8:47
1

You can use regular expression

if(/^-?\d+\.?\d*$/.test(1.23)) {
    // hurray this is a number
}
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.