Skip to content

Instantly share code, notes, and snippets.

@afonsomatos
Last active August 29, 2015 14:23
Show Gist options
  • Save afonsomatos/b2424fca4e9edf938113 to your computer and use it in GitHub Desktop.
Save afonsomatos/b2424fca4e9edf938113 to your computer and use it in GitHub Desktop.
Numbers' methods and new literals in es6
// Octals 0 + o + integer
0o8
// Binary 0 + b + integer
0b11
// ParseInt doesn't support binary literals
parseInt('0b11', 2); // 0
// Instead use Number()
Number('0b11'); // 3
// Or remove prefix
parseInt('11', 2); // 3
// Test if number is instance of Number, not (-)Infinity nor NaN
Number.isFinite(Infinity); // False
Number.isFinite(123); // True
// Doesn't coerce its parameter whereas the global does
isFinite('123'); // true
Number.isFinite('123'); // false
// Test if the object is NaN
Number.isNaN(NaN); // true
// Doesn't coerce its parameter to number
Number.isNaN('123'); // false
isNaN('123'); // true
// Same parseFloat and parseInt but now within Number
Number.parseFloat('22.5'); // 22.5
Number.parseInt('22.5'); // 22
// NUMBER.EPSILON specifies a margin of error when comparing floats
Math.abs(3.000000000000004 - 3) < Number.EPSILON; // true, so probably they are equal
Math.abs(4 - 3) < Number.EPSILON; // false
// Know if it's an integer (without decimal part)
Number.isInteger(33); // true
Number.isInteger('33'); // false
// Safe integers between range (−2^53, 2^53)
Number.isSafeInteger(Math.pow(2, 53) - 1); // true
Number.isSafeInteger(Math.pow(2, 53)); // false
Number.MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
Number.MIN_SAFE_INTEGER = -Number.MAX_SAFE_INTEGER;
// A calculation (a + b = c) gives a safe result if
Number.isSafeInteger(a) &&
Number.isSafeInteger(b) &&
Number.isSafeInteger(a + b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment