JAVASCRIPT

  minte9
REMEMBERS




Last update:   27-01-2022

Round

One of the most used operations, when working with numbers, is rounding.
 
/**
 * There are several built-in functions for rounding.
 */

let n = 1.23456;

let n1 = Math.round(n * 100) / 100; // 123 -> 1.23
console.log(n1); // 1.23

let n2 = n.toFixed(2); // "1.23"
console.log(1.23 === n2); // false

Precision

Internally, a number is represented in a 64-bit format.
 
/**
 * Losing precision
 * 
 * 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
 * 
 * Losing precision is quite common ...
 * and this is true for many other languages.
 */

let sum = 0.1 + 0.2;

console.log(sum); // 0.30000000000000004
console.log(sum.toFixed(2)); // "0.30"
console.log(+sum.toFixed(2)); // 0.3 - unary plus converts to number

Conversion

Parse functions read a number from a string, until they can't.
 
/**
 * In real life we ofthe have values like "100px" or "19$"
 * 
 * parseInt returns an integer
 * parserFloat returns a floating-point number 
 */

console.log(parseInt("100px")); // 100
console.log(parseInt("19$")); // 19

console.log(parseFloat("12.3")); // 12
console.log(parseFloat("12.3.4")); // 12.3 second point stop reading

Questions     github Types
Strings
        A B C D E F
🔔
1/2