myNumber.toString( [ radix ] ) in ECMAScript 262

Return the number as a string converted to a specified base.

Arguments

nametypedescription
radix Number [optional] The base to express the number
Return Type
String

Description

If radix is undefined, base 10 is assumed. The following code shows this method being used to express numbers in various bases:

var numbers = [8,10,12,16,200,255];
var bases = [2,8,10,16];
var msg="";
for (var i=0,len=numbers.length;i<len;i++){
    var n = numbers[i];
    for (var j=0,len2=bases.length;j<len2;j++){
        var base = bases[j];
        msg += n+' in base '+base+' is '+n.toString(base)+'\n';
    }
}
/****************************************
msg is:
8 in base 2 is 1000
8 in base 8 is 10
8 in base 10 is 8
8 in base 16 is 8
10 in base 2 is 1010
10 in base 8 is 12
10 in base 10 is 10
10 in base 16 is a
12 in base 2 is 1100
12 in base 8 is 14
12 in base 10 is 12
12 in base 16 is c
16 in base 2 is 10000
16 in base 8 is 20
16 in base 10 is 16
16 in base 16 is 10
200 in base 2 is 11001000
200 in base 8 is 310
200 in base 10 is 200
200 in base 16 is c8
255 in base 2 is 11111111
255 in base 8 is 377
255 in base 10 is 255
255 in base 16 is ff
****************************************/

Note that the returned string is not padded to any number of digits. The following convenience method shows how to extend the Number prototype to support a new method, which allows you to specify a certain number of digits desired; if less than that number is returned by the call to toString(), 0s are padded to the front.

Number.prototype.convertTo=function(base,padTo){
    var s=this.toString(base);
    if (!padTo || s.length>=padTo) return s;
    return Math.pow(10,padTo-s.length).toString().slice(1)+s;
}
var x = 12;
x.toString(2);     // ** "1100"
x.convertTo(2,8);  // ** "00001100"
x.convertTo(16,2); // ** "0c"