最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to compare two string values as integers? - Stack Overflow

programmeradmin3浏览0评论

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
  • Btw.: 9 and 09 are considered equal as 09 is not a valid number in octal and as such is interpreted as a decimal. – poke Commented Sep 26, 2012 at 9:20
  • Really? FF parses it to zero. – spender Commented Sep 26, 2012 at 9:21
  • @spender I’m using Firefox too; tested it in the web console, scratchpad, Firebug and JSTerm now. Same result, 09 == 9. – poke Commented Sep 26, 2012 at 9:23
  • That's strange because in my web console parseInt("09") == 0 – spender Commented Sep 26, 2012 at 9:23
  • Okay… strings; I was using numbers, as y=09 does not look like a string assignment to me. – poke Commented Sep 26, 2012 at 9:25
Add a comment  | 

2 Answers 2

Reset to default 16

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

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

发布评论

评论列表(0)

  1. 暂无评论