parseInt() method | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

parseInt() method

I have an understanding that the parseInt() method returns an integer value based on the string passed to it. And when given a second parameter is passed to it as a number, it will return the integer value of string based on the radix of the second parameter (e.g parseInt('245', 8) will return the integer value of the string in base 8). While learning about the parseInt() method, I also learnt that you can convert a number to it's string literal in a particular radix using toString(radix) method. (e.g from the first example I gave above, toString(10) will convert the returned octal value of the parseInt() method to decimal). I came across an exercise that asks you to write a function to convert a binary (base 2) number to decimal (base 10). Now I know there are a number of ways of do this but with my understanding of parseInt() method I was able to write the code like this: function bin_to_dec(base2str) { var base10 = parseInt(base2str, 2).toString(10); return base10; } document.write(bin_to_dec('100')) //outputs 4 This is correct as the solution they gave was also written somewhat like this. However while I was viewing codes of other participants, I came across a code that was written like this: function ex2(bin) { return parseInt(bin, 2); } document.write(ex2('100')) //outputs 4 This is also correct but I am confused because from what I have understood, the parseInt() method should have converted the string to the radix of that specified in the second parameter, in this case base 2 (i.e. the output should have been in base 2 from what I understand). What am I getting wrong? I am a beginner in JavaScript programming.

11th Oct 2020, 12:20 PM
Logos
Logos - avatar
2 Answers
+ 4
The second parameter indicates radix / base of string to be parsed. parseInt() always return integer and converting a number to string *implicitly* results in decimal representation.¹ For example, even if you write : console.log(0xf); it'll print 15. No need to explicitly convert to decimal. The whole point of second parameter is to tell in what radix the string represents number. It doesn't indicate the radix of return value. [1] Implicit convertion of number to string is like calling Number.prototype.toString([radix]) without any argument. The radix parameter defaults to 10. See the docs for Number#toString() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
11th Oct 2020, 12:31 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 2
Thank you very much, I understand your explanation. It makes sense now.
11th Oct 2020, 12:51 PM
Logos
Logos - avatar