BigInt), so you have to be a little careful. See this example:
console.log(3 / 2); // 1.5, not 1 console.log(Math.floor(3 / 2)); // 1
So an apparent integer is in fact implicitly a float.
Also, watch out for stuff like:
0.1 + 0.2 == 0.30000000000000004;
In practice, integer values are treated as 32-bit ints, and some implementations even store it that way until they are asked to perform an instruction that’s valid on a Number but not on a 32-bit integer. This can be important for bit-wise operations.
The standard arithmetic operators are supported, including addition, subtraction, modulus (or remainder) arithmetic, and so forth. There’s also a built-in object that we did not mention earlier called
Math that provides advanced mathematical functions and constants:
Math.sin(3.5); var circumference = 2 * Math.PI * r;
You can convert a string to an integer using the built-in
parseInt() function. This takes the base for the conversion as an optional second argument, which you should always provide:
parseInt('123', 10); // 123 parseInt('010', 10); // 10
In older browsers, strings beginning with a “0” are assumed to be in octal (radix 8), but this hasn’t been the case since 2013 or so. Unless you’re certain of your string format, you can get surprising results on those older browsers:
parseInt('010'); // 8 parseInt('0x10'); // 16
Here, we see the
parseInt() function treat the first string as octal due to the leading 0, and the second string as hexadecimal due to the leading “0x”. The hexadecimal notation is still in place; only octal has been removed.
If you want to convert a binary number to an integer, just change the base:
parseInt('11', 2); // 3
Similarly, you can parse floating point numbers using the built-in
parseFloat() function. Unlike its
parseFloat() always uses base 10.
You can also use the unary
+ operator to convert values to numbers:
+ '42'; // 42 + '010'; // 10 + '0x10'; // 16
A special value called
NaN (short for “Not a Number”) is returned if the string is non-numeric:
parseInt('hello', 10); // NaN
NaN is toxic: if you provide it as an operand to any mathematical operation, the result will also be
NaN + 5; // NaN
You can test for
NaN using the built-in
isNaN(NaN); // true
1 / 0; // Infinity -1 / 0; // -Infinity
You can test for
NaN values using the built-in
isFinite(1 / 0); // false isFinite(-Infinity); // false isFinite(NaN); // false
parseFloat() functions parse a string until they reach a character that isn’t valid for the specified number format, then return the number parsed up to that point. However the “+” operator simply converts the string to
NaN if there is an invalid character contained within it. Just try parsing the string “10.2abc” with each method by yourself in the console and you’ll understand the differences better.