Round
One of the most used operations, when working with numbers, is rounding.
/**
* Several built-in functions for rounding
*/
let n = 1.23456;
let a = Math.round(n * 100) / 100; // 123 -> 1.23
let b = n.toFixed(2); // "1.23"
console.log(a); // 1.23
console.log(1.23 === b); // false
Precision
Internally, a number is represented in a 64-bit format.
/**
* Losing precision is quite common
* and this is true for many other languages
*
* There are exactly 64 bits to store a number:
* 52 to store the digits
* 11 to store the position of decimal point
* 1 bit for the sign
*/
let sum = 0.1 + 0.2;
console.log(sum); // 0.30000000000000004
console.log(sum.toFixed(2) === "0.30"); // true
console.log(+sum.toFixed(2) === 0.3); // true (unary + converts to number)
Conversion
Parse functions read a number from a string, until they can't.
/**
* In real life, values like "100px" or "19$"
*
* parseInt() returns integer
* parserFloat() returns floating-point number
*/
console.log(parseInt("100px") === 100); // true
console.log(parseInt("19$") === 19); // true
console.log(parseFloat("12.3") === 12.3); // true
console.log(parseFloat("12.3.4") === 12.3); // true
// 12.3 second point stop reading
Last update: 357 days ago