-1

I don't understand what's happening here:

var x = 14;
alert(x.toString(36)); //alerts 'e'

alert(x.toString(16)); //also alerts 'e'

x = 20;
alert(x.toString(16)); //alerts '14'
alert(x.toString(36)); //alerts 'k'

I think the first parameter determines the numerical system of the number to be converted, but I am not sure. Can anybody explain in detail what exactly is going on?

Rasteril
  • 605
  • 1
  • 5
  • 16
  • Yes, I checked that answer. I needed some more information about using the method to convert to letters. – Rasteril Mar 01 '13 at 16:10
  • Do you mean that you are trying to get the letter that is represented by the character code '14'? – talemyn Mar 01 '13 at 16:20
  • @talemyn yes, the whole script is supposed to convert character codes into letters. I was unsure how the parameter could be used to perform such an operation. – Rasteril Mar 01 '13 at 16:28
  • 1
    @Rasteril anything higher than base 10 runs out of numerical digits and begins using the alphabet for digits. This is why 36 (10 digits + 26 letters) is the max. – jbabey Mar 01 '13 at 16:29
  • Thank you, that's exactly the answer I was looking for. – Rasteril Mar 01 '13 at 16:40

3 Answers3

3

You are changing the bases by passing the number parameter. The second example is easiest to explain . . . 14 in base16 is 'e'. The base16 'digits' are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a (10), b (11), c (12), d (13), e (14), and f (15).

For any number system of 15 or above, actually, 14 will = 'e'.

In the case of 20, base16 gives you 14, be cause you have 1 sixteen, plus 4 ones (16 + 4 = 20).

To level set, in decimal (base10 . . . the system that we are most used to), 14 technically is 1 ten plus 4 ones.

If you are not familiar with the different numbering systems, it can take a little getting used to. :)

talemyn
  • 7,822
  • 4
  • 31
  • 52
2

The parameter is the radix.

number.toString( [radix] )

See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString

The Number object overrides the toString method of the Object object; it does not inherit Object.toString. For Number objects, the toString method returns a string representation of the object in the specified radix.

The toString method parses its first argument, and attempts to return a string representation in the specified radix (base). For radixes above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), a through f are used.

If toString is given a radix not between 2 and 36, an exception is thrown.

If the radix is not specified, the preferred radix is assumed to be 10.

j08691
  • 204,283
  • 31
  • 260
  • 272
0

The optional argument is the radix.

Graham
  • 6,484
  • 2
  • 35
  • 39