Math Object

The JavaScript Math Object might not be used quite as often as the string object, but it is really useful when dealing with numbers. Sometimes we need to find the nearest integer to a number with a decimal (float). Other times, we need to do some sophisticated mathematics on them, such as powers or square roots. The math object is also where random number generation resides.

Number in JavaScript are really simple and so is the Math Object. However, I have sort of mislead you on numbers and the Math Object. See, the Math Object acts upon numbers, they do not utilize the Math Object as a method. As you will see in the examples below, we must perform the Math methods on our numbers. This is why you will see Math.method(number) being used in the references below. I know it seems like once you have a number it should have methods that do these Math Object Methods, but they simply don’t exist.

Common Math Object Methods

abs(x) – gets absolute value of x

Example

Result

1

ceil(x) – gets x rounded up to the nearest integer

Example

Result

3

floor(x) – gets x rounded up to the nearest integer

Example

Result

2

max(x,y,z,…) – gets the highest number of the arguments

Example

Result

5

min(x,y,z,…) – gets the lowest number of the arguments

Example

Result

5

pow(x,y) – gets x to the power of y

Example

Result

8

random() – generates random number between 0 and 1

Example

Result

0.6697745699866664

round(x) – gets x rounded to the nearest integer

Example

Result

3

sqrt(x) – gets the square root of x

Example

Result

4
If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Comment

  1. The description of ceil and floor should be restated (the given definition is the same as round), as follow:
    ceil(x) – gets x rounded up to the nearest integer greater or equal to x
    floor(x) – gets x rounded up to the nearest integer lesser or equal to x

  2. @chekkal, True but I think you mean floor(x) – gets x rounded DOWN

    I love this site, but there are a lot of typographical errors. I almost wish that we could edit it like wiki, but of course that would compromise the integrity of such a modest site (relative to the traffic on wiki). Still, I wish there was a better way to fix typos than leave a comment, as I doubt the developer has the time to read them all.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.