number
It represents both integer and floating point numbers.
The special numeric values also belong to this data type: Infinity
, -Infinity
and NaN
.
Infinity
(and -Infinity
) is a special numeric value that is greater (less) than anything.NaN
represents a computational error.
NaN
returns NaN
.NaN
is unique in that it does not equal anything, including itself.console.log(NaN === NaN); // false
console.log(isNaN(NaN)); // true
console.log(isNaN("str")); // true
isFinite(value)
converts its argument to a number and returns true if it’s a regular number, not NaN
, Infinity
, or -Infinity
.
isFinite
is used to validate whether a string value is a regular number:isFinite
.console.log(isFinite("15")); // true
console.log(isFinite("str")); // false, because a special value: NaN
console.log(isFinite(Infinity)); // false, because a special value: Infinit
Math computation is “safe” in JavaScript.
NaN
as the result.let billion = 1e9; // 1 billion, literally: 1 and 9 zeroes
console.log( 7.3e9 ); // 7.3 billions (7,300,000,000)
console.log( 1e-6 ); // Six zeroes to the left from 1, which is 0.000001
console.log( 0xff ); // 255
console.log( 0xFF ); // 255 (the same, case doesn't matter)
let a = 0b11111111; // binary form of 255
let b = 0o377; // octal form of 255
let num = 255;
// The base can vary from 2 to 36. By default it’s 10.
console.log(num.toString(16)); // ff
console.log(num.toString(2)); // 11111111
// If we want to call a method directly on a number, then we need to place two dots .. after it.
console.log(123456..toString(36)); // 2n9c
parseInt
and parseFloat
parseInt
and parseFloat
“read” a number from a string until they can’t.
parseInt
returns an integer, whilst parseFloat
will return a floating-point number.parseInt
/parseFloat
will return NaN
.
parseInt()
function has an optional second parameter.
parseInt
can also parse strings of hex numbers, binary numbers and so on.parseInt('100px'); // 100
parseFloat('12.5em'); // 12.5
parseInt('12.3'); // 12, only the integer part is returned
parseFloat('12.3.4'); // 12.3, the second point stops the reading
parseInt('a123'); // NaN, the first symbol stops the process
parseInt('0xff', 16); // 255
parseInt('ff', 16); // 255, without 0x also works
parseInt('2n9c', 36); // 123456
Math.floor
: Rounds down: 3.1 becomes 3, and -1.1 becomes -2.Math.ceil
: Rounds up: 3.1 becomes 4, and -1.1 becomes -1.Math.round
: Rounds to the nearest integer: 3.1 becomes 3, 3.6 becomes 4 and -1.1 becomes -1.Math.trunc
(not supported by IE): Removes anything after the decimal point without rounding: 3.1 becomes 3, -1.1 becomes -1.