You are here: irt.org | FAQ | JavaScript | Number | Q146 [ previous next ]
The following script will convert any decimal number to a any base upto 36:
<SCRIPT LANGUAGE="JavaScript"><!-- function makeArray() { for (i = 0; i<makeArray.arguments.length; i++) this[i] = makeArray.arguments[i]; } var convert = new makeArray('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'); function returnBase(number,base) { if (number < base) var output = convert[number]; else { var MSD = '' + Math.floor(number / base); var LSD = number - MSD*base; if (MSD >= base) var output = returnBase(MSD,base) + convert[LSD]; else var output = convert[MSD] + convert[LSD]; } return output; } document.write('Answer = ' + returnBase(510,16)); //--></SCRIPT>
Martin Honnen kindly pointed out the following solution:
<SCRIPT LANGUAGE="JavaScript"><!-- var n = 16; alert(n.toString(16)); //--></SCRIPT>
However, as Jukka Korpela points out:
it seems to me that at least on Internet Explorer 3.0 and Opera 3.60, the parameter (16) is ignored - and this means getting the wrong result without any warning. Since the toString solution is probably commonly suggested, perhaps it's useful to mention but with a warning that it does not work on all browsers, so it's better to use another solution.