Javascript string/integer comparisons

JavascriptHtml

Javascript Problem Overview


I store some parameters client-side in HTML and then need to compare them as integers. Unfortunately I have come across a serious bug that I cannot explain. The bug seems to be that my JS reads parameters as strings rather than integers, causing my integer comparisons to fail.

I have generated a small example of the error, which I also can't explain. The following returns 'true' when run:

javascript:alert("2">"10")

Javascript Solutions


Solution 1 - Javascript

Parse the string into an integer using parseInt:

javascript:alert(parseInt("2", 10)>parseInt("10", 10))

Solution 2 - Javascript

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

Solution 3 - Javascript

Comparing Numbers to String Equivalents Without Using parseInt
console.log(Number('2') > Number('10'));
console.log( ('2'/1) > ('10'/1) );

var item = { id: 998 }, id = '998';
var isEqual = (item.id.toString() === id.toString());
isEqual;

Solution 4 - Javascript

use parseInt and compare like below:

javascript:alert(parseInt("2")>parseInt("10"))

Solution 5 - Javascript

Always remember when we compare two strings. the comparison happens on chacracter basis. so '2' > '12' is true because the comparison will happen as '2' > '1' and in alphabetical way '2' is always greater than '1' as unicode. SO it will comeout true. I hope this helps.

Solution 6 - Javascript

You can use Number() function also since it converts the object argument to a number that represents the object's value.

Eg: javascript:alert( Number("2") > Number("10"))

Solution 7 - Javascript

The answer is simple. Just divide string by 1. Examples:

"2" > "10"   - true

but

"2"/1 > "10"/1 - false

Also you can check if string value really is number:

!isNaN("1"/1) - true (number)
!isNaN("1a"/1) - false (string)
!isNaN("01"/1) - true (number)
!isNaN(" 1"/1) - true (number)
!isNaN(" 1abc"/1) - false (string)

But

!isNaN(""/1) - true (but string)

Solution

number !== "" && !isNaN(number/1)

Solution 8 - Javascript

The alert() wants to display a string, so it will interpret "2">"10" as a string.

Use the following:

var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);

var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);

Solution 9 - Javascript

+ operator will coerce the string to a number.

console.log( +"2" > +"10" )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRonan SharpView Question on Stackoverflow
Solution 1 - JavascripticktoofayView Answer on Stackoverflow
Solution 2 - JavascriptRobGView Answer on Stackoverflow
Solution 3 - JavascriptCodyView Answer on Stackoverflow
Solution 4 - JavascriptSenthilView Answer on Stackoverflow
Solution 5 - JavascriptBimlendu KumarView Answer on Stackoverflow
Solution 6 - Javascriptuser13903251View Answer on Stackoverflow
Solution 7 - JavascriptOlegDovgerView Answer on Stackoverflow
Solution 8 - JavascriptSteveView Answer on Stackoverflow
Solution 9 - JavascriptEmeeusView Answer on Stackoverflow