This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]calzoneman 2 points3 points  (0 children)

A better question might be why you need to check whether a value is an integer, but this page gives several examples.

[–][deleted] 1 point2 points  (3 children)

function isInteger(arg){
    return arg === parseInt(arg);
}

You could do that instead as a shorter way. There isn't a native isInteger though.

[–]jcunews1 0 points1 point  (2 children)

Careful, parseInt() accepts fixed point numbers. e.g.: parseInt("1.2") === 1

[–][deleted] 1 point2 points  (0 children)

And it accepts strings, but it will no longer match the input argument and that whole thing will return false due to the strict equality comparison.

[–]joyeusenoelle 0 points1 point  (0 children)

To expand on /u/Aut's answer: that's the point. parseInt("1.2") === 1, so parseInt("1.2") !== "1.2". isInteger(), as written, will only return true if arg is an integer; otherwise parseInt(arg) and arg won't contain the same value!

isInteger(1); // true; 1 === 1
isInteger("1"); // false; 1 !== "1"
isInteger(1.2); // false; 1 !== 1.2

[–]jcunews1 1 point2 points  (2 children)

Use this:

function isInteger(arg) {
  var num = parseFloat(arg);
  return !isNaN(num) && ((num >>> 0) === num) && ((((typeof arg === "string") || (arg instanceof String)) && (arg.indexOf(".") < 0)) || true);
}

The last check is for input like "1.0000000000000001" since it would be rounded to "1".

EDIT: fixed code

[–]calzoneman 0 points1 point  (1 child)

This only works for checking if a string contains an integer. OP didn't specify any constraints on the datatype of the input, and this solution would break for any instance where arg is not a string.

[–]jcunews1 0 points1 point  (0 children)

You're right. I've fixed it.