Does .toString(16) always return lowercase?

ColBeseder picture ColBeseder · Nov 3, 2013 · Viewed 9.1k times · Source

When converting a decimal number to a base above 10 using .toString(base), it seems that I always get a lower case string. Can I rely on this? An upper case string would be correct, although would need converting for my application.

Extra credit for referencing the part of the spec that defines this (I looked and couldn't find it) and for any counter-examples (browsers that return uppercase).

Example:

(12648430).toString(16) // returns: "c0ffee". Not "C0FFEE"

Answer

T.J. Crowder picture T.J. Crowder · Nov 3, 2013

Probably. It's defined in the 5th edition specification, §15.7.4.2:

If ToInteger(radix) is not an integer between 2 and 36 inclusive throw a RangeError exception. If ToInteger(radix) is an integer from 2 to 36, but not 10, the result is a String representation of this Number value using the specified radix. Letters a-z are used for digits with values 10 through 35. The precise algorithm is implementation-dependent if the radix is not 10, however the algorithm should be a generalisation of that specified in 9.8.1.

(my emphasis)

But, the 3rd edition spec (from 1999) did not say that, it just said:

If radix is an integer from 2 to 36, but not 10, the result is a string, the choice of which is implementation-dependent.

...so it's possible you may find engines in the wild that use upper case (or something else entirely). I'd say that's fairly unlikely, they didn't usually add things like that to the spec if there were significant known implementations that didn't have that behavior. I get lower case on current versions of Chrome, Firefox, and Opera, and on IE8 and even IE6. So I'd say it's probably fairly consistent.