Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two string values as integers?

Tags:

javascript

I am converting and comparing two string values using

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

The problem is if values are x="9" and y="09" the test returns false.

How can I get fix this ?

like image 554
Anjana Avatar asked Sep 26 '12 09:09

Anjana


1 Answers

Use this :

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

If you don't precise the radix, "09" is parsed as octal (this gives 0).

MDN documentation about parseInt

Note that you shouldn't even rely on this interpretation when working with octal representations :

ECMAScript 5 Removes Octal Interpretation

The ECMAScript 5 specification of the function parseInt no longer allows implementations to treat Strings beginning with a 0 character as octal values. ECMAScript 5 states:

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

This differs from ECMAScript 3, which discouraged but allowed octal interpretation.

Since many implementations have not adopted this behavior as of 2011, and because older browsers must be supported, always specify a radix.

Simply :

always specify a radix

like image 85
Denys Séguret Avatar answered Sep 22 '22 00:09

Denys Séguret