How to compare two string values ​​as integers?

I convert and compare two string values ​​using

if (parseInt(x)!=parseInt(y)) { 

The problem is that the values x="9" and y="09" test return false .

How can i fix this?

+6
source share
2 answers

Use this:

 if(parseInt(x, 10)!=parseInt(y, 10)) 

If you do not specify the radius, "09" is parsed as octal (this gives 0).

MDN documentation about parseInt

Note that you should not rely on this interpretation when dealing with octal representations:

ECMAScript 5 removes octal interpretation

The ECMAScript 5 specification of the parseInt function no longer allows implementations to process strings starting with the character 0 as octal values. ECMAScript 5 says:

The parseInt function produces an integer value, determined by the interpretation of the contents of the string argument according to the specified radius. Exceeding a space in a line is ignored. If radix is ​​undefined or 0, it is assumed that it is 10, except when a number begins with pairs of characters 0x or 0X, in which case a radius of 16 is assumed to be. If radix is ​​16, the number may also optionally begin with a pair of 0x or 0X characters.

This is different from ECMAScript 3, which discourages but allows octal interpretation.

Since many implementations have not used this behavior since 2011, and since older browsers must be supported, always specify a radius.

Simply:

always indicate radius

+13
source

You need to set radix explicitelly to 10, otherwise it will assume that it is 8 (javascript bad parts):

 parseInt(x,10) 

http://www.w3schools.com/jsref/jsref_parseint.asp

If the line starts with "0", the radius is 8 (octal). This feature is deprecated.

+3
source

Source: https://habr.com/ru/post/926295/


All Articles