javascript.info Notes - Numbers
Quick notes about numbers in Javascript. It is expected that you have already understood how it works and just want to revise the important points.
let billion_1 = 1000000000;
let billion_2 = 1_000_000_000;
let billion_3 = 1e9;
//all above are same and equal
//all below are same and equal
let mсs_1 = 0.000001;
let mсs_2 = 0.000_001;
let mcs_3 = 1e-6; // five zeroes to the left from 1
I am ignoring Hex, binary and octal numbers as they are rarely used. Just check the documentation if needed.
.toString(base)
let num = 255;
alert( num.toString(16) ); // ff
alert( num.toString(2) ); // 11111111
//The base can vary from 2 to 36. By default it’s 10.
Rounding
Math.floor(3.1) // 3
Math.ceil(3.1) // 4
Math.round(3.1) // 3
Math.trunc(3.1) // 3
Math.floor(3.6) // 3
Math.ceil(3.6) // 4
Math.round(3.6) // 4
Math.trunc(3.6) // 3
//check documentation if any result does not make sense
//if we’d like to round the number to n-th digit after the decimal
let pi = 3.14159265359;
pi.toFixed() // 3
pi.toFixed(1) //3.1
pi.toFixed(2) // 3.14
pi.toFixed(3) //3.142
pi.toFixed(4) //3.1416
pi.toFixed(5) //3.14159
Note: NaN, Infinity can be tricky. Check stackoverflow if needed.
parsing numbers from string
alert( parseInt('100px') ); // 100
alert( parseFloat('12.5em') ); // 12.5
alert( parseInt('12.3') ); // 12, only the integer part is returned
alert( parseFloat('12.3.4') ); // 12.3, the second point stops the read
Misc useful Math functions:
Math.random()
//Returns a random number from 0 to 1 (not including 1).
Math.max(3, 5, -10, 0, 1) // 5
Math.min(1, 2, 3, 5) // 1
Math.pow(2, 10) // 2 ^ 10 = 1024
Refer to Math object documentation if more detail is needed.