Javascript Math Object

The Math object is very different from all of the other objects that you will work with in JavaScript because it is the one object where you never need to create copies. Instead all of the methods and properties of the math object are static and can be accessed directly.

We'll start by looking at the properties of our static math object. These are all actual constant values which are more easily referenced by name rather than trying to remember what the specific value is. In each case the number of decimal places that the number will have will be as many as the JavaScript implementation allows since all of these named number values have an infinite number of decimals in their true values.

Math.PI         (3.14159...)
Math.E          (2.718...)
Math.LN2        (0.693...)
Math.LN10()     (2.302...)
Math.LOG10E()   (0.434...)
Math.SQRT1_2()  (0.707...)
Math.SQRT2      (1.414...)

The methods available via the Math object provide a lot of the normal mathematical functions that you would expect (assuming that you can remember the mathematics that you studied in high school) as well as a number of functions for comparing and manipulating numbers.

Math.abs(number)

absolute value

Math.acos(number)

arc cosine (in radians)

Math.asin(number)

arc sine (in radians)

Math.atan(number)

arc tangent (in radians)

Math.cos(num_radians)

cosine

Math.sin(num_radians)

sine

Math.tan(num_radians)

tangent

Math.ceil(number)

smallest integer greater than or equal to the number

Math.floor(number)

largest integer less than or equal to the number

Math.exp(number)

e to the power of number

Math.log(number)

natural log of number

Math.pow(base,exponent)

base to exponent power

Math.max(number,number)

greater of the two (or more) numbers

Math.min(number,number)

smaller of the two (or more) numbers

Math.round(number)

rounds the number to the nearest integer

Math.sqrt(number)

finds the square root of the number

The Math methods that you will probably use most frequently are Math.floor, Math.round and Math.ceil all of which have the effect of converting the number passed to it into an integer. The only difference between the three is the rule that is followed in working out which way to round the number. Of the three discarding the fraction by using Math.floor will probably be the most useful.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate