Anurag Ratna
Anurag Ratna

Reputation: 311

JavaScript Puzzle: Not able to understand parseInt results in JavaScript

Can someone please explain why we are getting following results in JavaScript?

parseInt ( 'a' , 24 ) === 24 ;
>false
parseInt ( 'a' , 34 ) === 24 ;
>false
parseInt ( 'o' , 34 ) === 24 ;
>true

Upvotes: 0

Views: 154

Answers (2)

Raghvendra Kumar
Raghvendra Kumar

Reputation: 1388

The second argument to parseInt(string, radix); is a integer between 2 and 36 that represents the radix of the first argument string.

The return value of parseInt(string, radix); will be the decimal integer representation of the first argument taken as a number in the specified radix.

Now,keeping that in mind if you convert them :

      Input            Output   

  a (base-24)        10 (base-10)
  a (base-34)        10 (base-10)
  o (base-34)        24 (base-10)

So, as you can see in third case it comes out to be 24 and bingo! there you go the condition is true.

You can use any online tool to convert from one number system to another like I used this one :

http://extraconversion.com/base-number/base-34

Hope this Helps!

Upvotes: 1

Bill the Lizard
Bill the Lizard

Reputation: 405735

The second argument to parseInt is the radix.

In base 24 or 34, 'a' is equal to 10 because it is the first letter of the alphabet, so it's the first digit used after the digits 0-9. 'o' is the 15th letter of the alphabet, so it is equal to 24 in bases that have that many digits, like your last example of 34.

Upvotes: 2

Related Questions