As with strings and arrays, JavaScript provides some built-in methods for the
Math
object. These allow us to perform calculations or tasks that are more
involved than simple multiplication, division, addition, or subtraction.
The Math
object contains over 30 methods. The table below provides a sample
of the most frequently used options. More complete lists can be found here:
To see detailed examples for a particular method, click on its name.
Method | Syntax | Description |
---|---|---|
abs | Math.abs(number) |
Returns the positive value of number . |
ceil | Math.ceil(number) |
Rounds the decimal number UP to the closest integer value. |
floor | Math.floor(number) |
Rounds the decimal number DOWN to the closest integer value. |
max | Math.max(x,y,z,...) |
Returns the largest value from a set of numbers. |
min | Math.min(x,y,z,...) |
Returns the smallest value from a set of numbers. |
pow | Math.pow(x,y) |
Returns the value of x raised to the power of y (x y). |
random | Math.random() |
Returns a random decimal value between 0 and 1, NOT including 1. |
round | Math.round(number) |
Returns number rounded to the nearest integer value. |
sqrt | Math.sqrt(number) |
Returns the square root of number . |
trunc | Math.trunc(number) |
Removes any decimals and returns the integer part of number . |
Follow the links in the table above for the floor
, random
, round
,
and trunc
methods. Review the content and then answer the following
questions.
Question
Which of the following returns -3
when applied to -3.87
?
Math.floor(-3.87)
Math.random(-3.87)
Math.round(-3.87)
Math.trunc(-3.87)
Question
What is printed by the following program?
1let num = Math.floor(Math.random()*10);
2
3console.log(num);
Question
What is printed by the following program?
1let num = Math.round(Math.random()*10);
2
3console.log(num);