Checking that strings are integers is separate to comparing if one is greater or lesser than another. You should always compare number with number and string with string as the algorithm for dealing with mixed types not easy to remember.

```
'00100' < '1' // true
```

as they are both strings so only the first zero of '00100' is compared to '1' and because it's charCode is lower, it evaluates as lower.

However:

```
'00100' < 1 // false
```

as the RHS is a number, the LHS is converted to number before the comparision.

A simple integer check is:

```
function isInt(n) {
return /^[+-]?\d+$/.test(n);
}
```

It doesn't matter if n is a number or integer, it will be converted to a string before the test.

If you really care about performance, then:

```
var isInt = (function() {
var re = /^[+-]?\d+$/;
return function(n) {
return re.test(n);
}
}());
```

Noting that numbers like 1.0 will return false. If you want to count such numbers as integers too, then:

```
var isInt = (function() {
var re = /^[+-]?\d+$/;
var re2 = /\.0+$/;
return function(n) {
return re.test((''+ n).replace(re2,''));
}
}());
```

Once that test is passed, converting to number for comparison can use a number of methods. I don't like *parseInt()* because it will truncate floats to make them look like ints, so all the following will be "equal":

```
parseInt(2.9) == parseInt('002',10) == parseInt('2wewe')
```

and so on.

Once numbers are tested as integers, you can use the unary + operator to convert them to numbers in the comparision:

```
if (isInt(a) && isInt(b)) {
if (+a < +b) {
// a and b are integers and a is less than b
}
}
```

Other methods are:

```
Number(a); // liked by some because it's clear what is happening
a * 1 // Not really obvious but it works, I don't like it
```

0
Created by RobG on 2020-03-11 20:56:41 +0000 UTC

Share