Skip to content

Instantly share code, notes, and snippets.

@SanjeQi
Last active December 10, 2018 14:07
Show Gist options
  • Save SanjeQi/3a2c01d7ac3743108fe148e5881c42d2 to your computer and use it in GitHub Desktop.
Save SanjeQi/3a2c01d7ac3743108fe148e5881c42d2 to your computer and use it in GitHub Desktop.
Number.isInteger()
Number.isInteger(42);
//=> true
Number.isInteger(0.42);
//=> false
------------------------------
Number.isFinite()
Number.isFinite(9001);
//=> true
Number.isFinite(Infinity);
//=> false
-------------------------------
Number.isNaN()
Number.isNaN(10);
//=> false
Number.isNaN(undefined);
//=> false
Number.isNaN(NaN);
//=> true
--------------------------------
Number.parseInt()
#Accepts a string as its first argument and parses it as an integer.
#The second argument is the base that should be used in parsing (e.g., 2 for binary or 10 for decimal).
#For example, 100 is 100 in decimal but 4 in binary:
Number.parseInt('100', 10);
//=> 100
Number.parseInt('100', 2);
//=> 4
--------------------------------------
Number.parseFloat()
#Number.parseFloat() only accepts a single argument, the string
#that should be parsed into a floating-point number:
Number.parseFloat('3.14159');
//=> 3.14159
---------------------------------------
Math.ceil() / Math.floor() / Math.round()
#JavaScript provides three methods for rounding numbers. Math.ceil() rounds the number up,
#Math.floor() rounds the number down,
#and Math.round() rounds the number either up or down, whichever is nearest:
Math.ceil(0.5);
//=> 1
Math.floor(0.5);
//=> 0
Math.round(0.5);
//=> 1
Math.round(0.49);
//=> 0
----------------------------------------
Math.max() / Math.min()
#These two methods accept a number of arguments and return the lowest
#and highest constituent, respectively:
Math.max(1, 2, 3, 4, 5);
//=> 5
Math.min(1, 2, 3, 4, 5);
//=> 1
----------------------------------------
Math.random()
#This method generates a random number between 0 (inclusive) and 1 (exclusive):
Math.random();
//=> 0.4495507082209371
#In combination with some simple arithmetic and one of the rounding methods, we can
#generate random integers within a specific range. For example, to generate a random integer between 1 and 10:
Math.floor(Math.random() * 10) + 1;
//=> 8
Math.floor(Math.random() * 10) + 1;
//=> 1
Math.floor(Math.random() * 10) + 1;
//=> 6
#Math.random() returns a number between 0 and 0.999..., which we multiply
#by 10 to give us a number between 0 and 9.999.... We then pass that number to Math.floor(), which
#returns an integer between 0 and 9. That's one less than the desired range (1 to 10), so we add one
#at the end of the equation. Try it out in the JS console!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment