JavaScript Data Type: Numbers
Numbers in JavaScript are stored in 64-bit format IEEE-754, also known as double precision floating point numbers.
In JavaScript, you shorten a number by appending the letter "e" to the number and specifying the zeroes count. In other words, "e" multiplies the number by 1 with the given zeroes count. For example:
var billion = 1e9; // 1 billion, literally: 1 and 9 zeroes
alert(5.4e6); // 5400000
A negative number after "e" means a division by 1 with the given number of zeroes. For example:
alert(2e-4); // 0.0002
Hex, Binary and Octal Numbers
Hexadecimal numbers are widely used in JavaScript to represent colors, encode characters, and for other things. There exists a shorter way to write them: 0x and then the number. For example:
alert(0xff); // 255
Binary and octal numeral systems are rarely used, but also supported using the 0b and 0o prefixes. for example,
var a = 0b11111111; // binary form of 255
var b = 0o377; // octal form of 255
alert(a == b); // true, the same number 255 at both sides
Rounding Numbers
One of the most used operations when working with numbers is rounding. There are several built-in functions for rounding:
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
Removes anything after the decimal point without rounding: 3.1 becomes 3, -1.1 becomes -1.
Math Functions
JavaScript has a built-in Math object which contains a small library of mathematical functions and constants.
Math.random()
Returns a random number from 0 to 1 (not including 1).
alert('Random Number: ' + Math.random());
Math.max(a, b, c) / Math.min(a, b, c)
Returns the greatest or smallest from the arbitrary number of arguments.
Math.pow(n, power)
Returns n raised the given power