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 ?
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 ?
Share Improve this question edited Nov 13, 2012 at 9:41 Denys Séguret 382k90 gold badges810 silver badges775 bronze badges asked Sep 26, 2012 at 9:18 AnjanaAnjana 1,4535 gold badges23 silver badges33 bronze badges 5 |2 Answers
Reset to default 16Use 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
You need to set the radix explicitelly to 10 otherwise it assume it is 8 (javascript bad parts):
parseInt(x,10)
http://www.w3schools.com/jsref/jsref_parseint.asp
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
9
and09
are considered equal as09
is not a valid number in octal and as such is interpreted as a decimal. – poke Commented Sep 26, 2012 at 9:2009 == 9
. – poke Commented Sep 26, 2012 at 9:23parseInt("09") == 0
– spender Commented Sep 26, 2012 at 9:23y=09
does not look like a string assignment to me. – poke Commented Sep 26, 2012 at 9:25