13

How can I simply check if string can be converted to integer?

And I mean only integer, so string like '10.1' would not be converted to 10.

For example if I do:

parseInt('10.1', 10)

It returns 10

Is there something equivalent like it is in Python, so I would not need to do lots of checks?

In Python if I do int('10.1'), it gives me error, but if string is actually integer, only then it lets you convert it like int('10'). So it is very easy to check that without even using regex or some additional checks.

I tried this:

    function isInteger (value) {
        if ($.isNumeric(value) && Number(value) % 1 === 0){
            return true;
        } else {
            return false;
        }
    }

It kinda works, but if I write for example 10., it will return true, because Number converts to 10. I guess I need to use regex to check such thing?

P.S. I searched for this question, but all answers seem to be vague and actually does not answer how to properly check for integer (not just if it is number).

3

7 Answers 7

24

One possibility is to use a regex to test, like so:

function isInteger(value) {
  return /^\d+$/.test(value);
}
Sign up to request clarification or add additional context in comments.

3 Comments

From ^ start to $ end + every character should be a \d number, right?
@Walter yep exactly
Watch out for scientific notation.
5

If i understand your question correctly then this should do it:

function isInteger(value) {
  if(parseInt(value,10).toString()===value) {
    return true
  }
  return false;
}

It converts a string to an integer and then back to a string and compares that to the original string. If they match, then it returns true, else it returns false.

4 Comments

@PeeHaa I see, but thats what I needed, because I only needed to be true for strings like '123' and if it would contain any non integer symbol (even if it represents hexadecimal), it should be false. I guess more specific way would be to use parseInt(val, 10), to show that I only care for decimals.
What is what you needed? Different returns for different implementations for JS vms?
Why isn't it needed? Enlighten me please? The page clearly tells us that when not defining the the radix the different implementation basically just do something and worse might / probably will just do something different than others.
As long as it is a decimal formatted string coming in, then parseInt will default to a radix of 10. Only JavaScript older than the Ecmascript 5 (from before 2009!) might have a problem, and then only with leading 0. I agree it is safer but not necessarily necessary.
2

I know this is quite old topic,
but i'd like to share a more elegant way of doing so.

As all JavaScript objects inherit properties and methods from prototypes and native types are mediated by objects, we should be able to define custom attributes on them.

I'm used to have a js file that defines usefull stuff as follows

Object.defineProperty(String.prototype, 'isInt', {
    get: function () {
        let number = parseFloat(this)

        if (!/^\-?[0-9]+\.[0-9]+$/gm.test(this) && !/^\-?[0-9]+$/gm.test(this)) return false  
        return number >= -2147483648 && number <= 2147483647 && number % 1 == 0
    }
})

once included, you're able to check if a string is an Integer like that

let str1 = "10"
let str2 = "10.1"

str1.isInt // true
str2.isInt // false

Note that the actual implementation is also checking that the value is a valid 4 byte integer (Int32), you can remove the number >= -2147483648 && number <= 2147483647 part to match any integer value (i'm currently doing so with an almost identic isLong attribute)

You can check the following snippet to test the outputs

const input = document.querySelector("input")
const button = document.querySelector("button")
const label = document.querySelector("label:nth-of-type(2)")

// isInt attribute
Object.defineProperty(String.prototype, 'isInt', {
    get: function () {
        let number = parseFloat(this)

        if (!/^\-?[0-9]+\.[0-9]+$/gm.test(this) && !/^\-?[0-9]+$/gm.test(this)) return false  
        return number >= -2147483648 && number <= 2147483647 && number % 1 == 0
    }
});

button.addEventListener("click", function(e) {
  label.innerHTML = input.value.isInt
})
<input/>
<button>evaluate</button>
<label>IsInteger:</label>
<label></label>

2 Comments

Great answer. It, doesn't seem to work for negative integers though. Need to add \-? before the first [0-9] in both test regex patterns.
You're 100% right. Answer has been updated, thanks for pointing it out.
1

You can use isNaN:

!isNaN(Number(value))

Explanation: Number = is a type ( like Int / String ), but can be used as a function, so Number(value) will try to convert any value to a Number type. But if it does not succeed - it results with NaN

// Number("2") => 2
// Number("two") => NaN

Then, you can use the function isNaN to check if the conversion has succeeded or not.

isNaN(Number(value))

// isNaN(Number("2")) => false, as the conversion succeeded.
// isNaN(Number("two")) => true, as the conversion did not succeeded.

1 Comment

Please elaborate on your answer, provide test data and explain.
0

You can use

Number function of js (http://www.w3schools.com/jsref/jsref_number.asp)

or

parseInt function of js (http://www.w3schools.com/jsref/jsref_parseint.asp)

Comments

0

You can use regex to detect if it match any value.

function isInterger(value) {
     if (value.match(/^\d+$/) {
        return true;
   } else {
        return false;
   }
}

https://regex101.com/r/lE5tK1/1

3 Comments

But I specifically said, I need to check for integer, not any number.
This matches any string which contains a number, e.g. "100foo", or "csdvsd7" would be matches
Yeah, I changed it! ;)
0

You could take advantage of Number.isInteger with a number.

function isInteger(v) {
    return Number.isInteger(+v);
}

console.log(isInteger(1.1));   // false
console.log(isInteger('1.1')); // false
console.log(isInteger(1));     //  true
console.log(isInteger('1'));   //  true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.