js Math Object

Textbook Chapter 6: Functions and Procedures

In this chapter we will learn how to call JavaScript and VBScript functions and procedures that can be reused to change the order in which action statements are executed.

Built-in Functions and Methods

When an object contains a built-in function it is referred to as a method. Built in functions include mathematical, date and time, string and formatting functions. Some are common to both JavaScript and VBScript, and some are unique to that scripting language.

JavaScript Math Object Methods

JavaScript includes a built-in math object which exposes many mathematical methods. As we've learned, a method is a function that is defined within an object. To access the abs method of the Math object, we can use the syntax: Math.abs(). The table below identifies several of the common mathematical methods that JavaScript supports.

Method      Description ExampleResult   
AbsReturns the absolute value of a numberMath.abs(-2)2
Floor Rounds number to next lowest integer Math.floor(7.1) 7
Ceil Rounds number to next highest integer Math.ceil(7.1) 8
Random Returns a random number between 0 and 1     Math.random() varies
Round Rounds the number to the nearest integer Math.round(7.5)     8
MinReturns the lowest of two numbersMath.min(3,4)3
MaxReturns the highest of two numbersMath.max(3,4)4

The following code uses the random method of the math object to select a random number between 0 and 1.

<script language="javascript">
var randNum=Math.random();
document.write(randNum);
</script>

Check out the EXAMPLE.