15.7.4.2 Number.prototype.toString([radix])

2010-07-11

string Number.prototype.toString([radix:uint|mixed=10]) throws RangeError

Convert this number to a string, optionally specifying the radix.

The radix should be a number between 2 and 36 inclusive. If radix is undefined, it is set to 10.

If ToInteger(radix) is not 2 ... 36 a RangeError is thrown.

If ToInteger(radix) === 10, the result is ToString(this.[[PrimitiveValue]]) (9.8.1).

If ToInteger(radix) !== 10 and no RangeError is thrown, the number is converted to string, where a single digit value of 10 through 35 is replaced by the lowercase alphabet letters a ... z. How this is done specifically is implementation specific, but it should be a generalization of ToString (9.8.1).

This method throws a TypeError if this is not a number or number object.

No explicit algorithm is given but...

Code: (Meta Ecma)
Number.prototype.toString = function(radix){
if (Type(this) != 'Number' && (Type(this) != 'Object' || this.[[Class]] != 'Number')) throw TypeError;
if (radix === undefined) radix = 10;
else radix = ToUint32(radix,10);
if (radix < 2 || radix > 36) throw RangeError;
if (radix == 10) return ToString(this.[[PrimitiveValue]]);
return s+''; // i cheat, yes :)
}

Note: According to 15.7.4.5 toString only results in enough digits to distinguish the number from an adjacent number. This is not noted under this paragraph. Examples:

(1000000000000000128).toString => "1000000000000000100"
(1000000000000000128).toFixed(0) => "1000000000000000128"