-1

i want to convert a number from decimal to binary, and i instantly remembered that parseInt also has a base argument, and just to be sure, i ran the following code:

parseInt('123', 2);

and the output was... 1?

after that I checked developer mozzila, and the second argument WAS the base, then I tried base 3, and the output was 5!!!!! this shouldn't be possible in base 3!

What am I doing wrong???

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • 1
    `parseInt('123', 10)` – Jared Farrish May 27 '21 at 21:08
  • `parseInt` parses the string until the first invalid character. "2" is an invalid character base 2. – ASDFGerte May 27 '21 at 21:10
  • the digits 2 and 3 are meaningless for base-2 numbers – Pointy May 27 '21 at 21:10
  • 1
    Also, `'123'` is not a number; it's a string. If you want a binary equivalent, convert `'123'` to a plain JavaScript number, and then use `.toString(2)` to get your binary equivalent (as another string). – Pointy May 27 '21 at 21:12
  • both of the answers are correct and useful... what do i do??? i cant mark both of them as correct –  May 27 '21 at 22:12

2 Answers2

2

The radix argument represents the radix of the input number not output number.

parseInt('1111', 2); // returns 15

From MDN parseInt():

parseInt(string, radix)

radix

An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string.

Samuel Olekšák
  • 389
  • 4
  • 12
2

The output is ALWAYS an integer. If you really want to use this method you only can covert in your case binary into an integer.

So if you try: parseInt("10101",2) the result would be 21. And this is correct. But in your case you provide to the method absolute invalid arguments because you may only use 0 and 1 for a binary input. The conversion goes left to right. The first invalid value will force to return the result without further compute.

Your 1st case: parseInt('123',2) The number 2 is an invalid binary value. This will make to finish after the 1 as input, which is a 1 as integer. It is correct.

Your 2nd try: parseInt('123', 3)

The last number 3 is invalid for a base of 3 with 0,1,2 as valid numbers. And if you convert the number 12 with the base of 3 the result is 5. From my point of view the method works as expected.