This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Converting and Checking Numbers --- | |
// By default numbers are treated as floating by javaScript | |
// Stores the number in binary (0 or 1) to hold numbers, we see weird results | |
console.log(10 === 10.0); // true | |
console.log(0.1 + 0.2); // 0.30000000000000004 | |
console.log(0.1 + 0.2 === 0.3); // false | |
// Converting to numbers | |
console.log(Number('10')); | |
console.log(+'10'); | |
// Parsing | |
console.log(Number.parseInt('20px', 10)); // 20 Note: 10 is redex base 10 to avoid few issues, When we work with binary use 2 | |
console.log(Number.parseInt('e20')); // NAN | |
console.log(Number.parseInt('2.5%', 10)); // 2 | |
console.log(Number.parseFloat('2.5%', 10)); // 2.5, having space before will also work | |
// Check the value is not a number | |
console.log(Number.isNaN(10)); // false | |
console.log(Number.isNaN('10')); // false | |
console.log(Number.isNaN(+'10')); | |
console.log(Number.isNaN(10 / 0)); | |
// Check the value is a number (this is better way) | |
console.log(Number.isFinite(10)); | |
console.log(Number.isFinite('10')); | |
console.log(Number.isFinite(+'10')); | |
console.log(Number.isFinite(10 / 0)); | |
console.log(Number.isInteger(10)); | |
console.log(Number.isInteger(10.0)); | |
console.log(Number.isInteger(10 / 0)); | |
---------------------------------------------------- | |
== Math and Rounding === | |
console.log(Math.sqrt(25)); | |
console.log(25 ** (1 / 2)); // Same as above | |
console.log(8 ** (1 / 3)); | |
console.log(Math.max(5, 19, 24, 13, 4)); | |
console.log(Math.max(5, 19, '24', 13, 4)); | |
console.log(Math.max(5, 19, '24px', 13, 4)); | |
console.log(Math.min(5, 19, 24, 13, 4)); | |
console.log(Math.PI * Number.parseFloat('5px') ** 2); // Area of circle | |
// Math.random() --> returns number b/w 0 and 1 | |
// Math.trunc() --> To remove decimal | |
console.log(Math.trunc(Math.random() * 6) + 1); // value b/w 1 and 6 | |
// Function to generate random number | |
const randomInt = (min, max) => Math.trunc(Math.random() * (max - min) + 1) + min; | |
console.log(randomInt(10, 20)); | |
// Rounding Integers | |
console.log(Math.trunc(14.3)); // cut of decimal part | |
console.log(Math.floor(14.3)); // cut of decimal part / floor is beter to work with -ve also | |
console.log(Math.floor(14.9)); // cut of decimal part | |
console.log(Math.round(14.3)); // round based on < .5 and > .5 | |
console.log(Math.round(14.9)); | |
console.log(Math.ceil(14.3)); // Round to next number | |
console.log(Math.ceil(14.9)); | |
// Rounding decimal | |
console.log((3.7).toFixed(0)); // Always returns string | |
console.log((3.7).toFixed(3)); | |
console.log((3.7554).toFixed(2)); | |
console.log(+(3.7554).toFixed(2)); // To get the number |