Numbers

Convert Strings to Number

parseInt('123', 10); // 10 is the base. In old browsers, strings start with 0 will be converted in octal (base 8).
// parseFloat() always uses base 10
+ '42';   // 42
+ '010';  // 10
+ '0x10'; // 16. 0x is 16-based.
parseInt('123abc', 10); // 123
+ '123abc'; // NaN
// Number(str) is the same as + str
// for +, if both perands are numbers, add them. otherwise, convert to strings and concat.
+'3' + (+'4') // 7

NaN: Not a number

typeof NaN; // number
NaN === NaN; // false
NaN !== NaN; // true
isNaN(NaN); // true
isNaN("Hello"); // true. Try to convert "Hello" to a number and results in NaN
isFinite(NaN); // false
isFinite(-Infinity); // false

This is faster than Math.floor. Note that for negative numbers, ~~(-5.423451) === -5 but Math.floor(-5.423451) === -6.

Scientific Number Literals

Interesting Arithmetics

The answer is 2 in JavaScript (same as a lot of other programming languages), which is obviously wrong. This is due to the inaccurate nature of floating point numbers. Actually if you type 9999999999999999.0 in the console, it would return 10000000000000000. Since 9999999999999999.0 is larger than Number.MAX_SAFE_INTEGER (9007199254740991), we really should not be surprised at any weird arithmetic results.

Last updated

Was this helpful?