# Math and Numbers
# Global Numerical Methods
There are a number of methods which can be called globally. This means that you do not have to place an object and a dot in front of the method call. Just call the method directly.
parseInt(str, base); //returns a string representation of the integer.
//The second parameter is the radix, or base. This means you can convert the integer
//to binary (base 2), octal (base 8), decimal (base 10), or hexidecimal (base 16)
//The base can be entered as any number between 2 and 36
parseFloat(str); //returns a string representation of the decimal number.
2
3
4
5
MDN reference for Global Objects
# Methods called by Number objects
When you have variables that are of datatype Number, there are a variety of methods that you can call on these variables.
num.toFixed(2); //round off the number to a specific number of decimal points
//Method returns a STRING
num.parseInt(); //convert the number to an integer.
//Method returns an integer
num.isNaN(); //check if the number in the variable is Not A Number (NaN)
//returns a true or false (Boolean)
num.isInteger(); //checks if the value in the variable is an integer.
//returns true or false. False if the number has decimals eg: 3.14
2
3
4
5
6
7
8
MDN reference for Number objects
# Mathematical methods
JavaScript has a Math object which can carry out most common mathematical operations. If you need to round numbers up or down, complete Trigonometric calculations, determine which is the largest or smallest number, create a random number, determine if a number is positive or negative, or access the value of Pi
. All of these things can be accomplished with the Mathematical methods.
These methods all begin with the Math
object name.
Math.round(num); //returns the next highest or lowest integer depending on its decimal value.
Math.floor(num); //always rounds down to the next lowest integer
Math.ceil(num); //always rounds up to the next highest integer
Math.random(); //returns a random value between 0 and 1.
Math.max(list, of, numbers); //returns the largest number from the list
Math.min(list, of, numbers); //returns the smallest number from the list
Math.abs(num); //returns the absolute value of the number
Math.sign(num); //returns 1, -1, 0, -0, NaN to tell you if the number is positive or negative
Math.sin(radians); //returns the sine value for the provided radian value
Math.cos(radians); //returns the value of Cosine for the provided radian value
Math.tan(radians); //returns the value of Tangent for the provided radian value
Math.PI; //Use this as if it were a variable holding the value of Pi
2
3
4
5
6
7
8
9
10
11
12
And there are many more Numeric and Mathematical methods available. I encourage you to read through the list on the MDN site.