2

I use parseInt to convert string to hex value but result of parseInt("BG", 16) is 11. I think it must be NaN. What's happening here?

adiga
  • 34,372
  • 9
  • 61
  • 83
  • 2
    The same reason `parseInt("12abc")` returns 12. *"If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point."* – adiga Jun 21 '19 at 03:32

2 Answers2

2

The second argument to parseInt is the radix. In base 16, "B" in "BG" corresponds to 11 (9 = 9, 10 = A, 11 = B), and G is not in the range of base 16 (which is 0-9 and A-F), so it gets ignored.

So, the result is the same as parseInt('B', 16):

console.log(parseInt('B', 16));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN.

parseInt

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

Here in first example B can be parsed to integer so it returns, but in second example G is out of range of Hex values so it returns NaN

console.log(parseInt("BG", 16))
console.log(parseInt("GB", 16))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60