0

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
2
  • 2
    It's because the digits (for bases larger than 10, same as in hex) are represented with letters: a == decimal 10, b == decimal 11... and so on until you get to o in base 34 in your last line -- which is 24 in decimal Commented Dec 3, 2014 at 15:15
  • ES5 15.1.2.2: "Let mathInt [the parsed value] be the mathematical integer value that is represented by Z [the input string] in radix-R notation, using the letters A-Z and a-z for digits with values 10 through 35." Commented Dec 3, 2014 at 15:28

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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!

3 Comments

thanks for clearing the concept in such a simple terms. one more thing,can you please tell me why secong args that is radic can take values from 2 to 36?
A number system is based on the different kinds of symbols it has to represent the numbers. For example if you take binary you just have two supported symbols '0' and '1'. So if you take all the symbols from Indo-Arabic Numerals(0,1,2,3,4,5,6,7,8,9) and Latin letters(a-z), you will have a maximum of 36 different symbols to represent a number in such a number system. That's why Javascript function parseInt supports up to 36 as radix.
Please mark it as your answer if it answers your question and if you want, you can make your second question from your comments as a separate question so that people can find it in search results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.