9.3 ToNumber

2010-05-04

number ToNumber(input:mixed)

Convert the input to a number. Always returns at least some kind of number, but may return NaN. There's a special paragraph (9.3.1) dedicated to converting strings to numbers. This will be briefly touched below.

Code: (Meta Ecma)
function ToNumber(input){
if (input === undefined) return NaN;
if (input === null) return +0;
if (input === true) return 1;
if (input === false) return 0;
if (typeof input == 'number') return input;
if (typeof input == 'object') return ToNumber(ToPrimitive(input, "Number"));
// else type must be string...
// apply special grammer to parse into a number and return the result
}

Basically, converting a string to a number is almost the same as how number literals are parsed. There are some minor differences though. Whitespace and LineTerminators are ignored. Decimals may have any number of leading zero's. Decimals may be preceeded by + or - for its sign. An empty string or a string with just whitespace is converted to +0.