6: Working with the Math object

Exploring the Math object and its various methods for working with integers, floats, maximum and minimum vales, and generating random numbers.

Learning Goals

At the end of this Tutorial, you will be able to:

  • Use various methods of the Math object to manipulate positive and negative numbers, convert between integers and floats, find maximum and minimum values, and generate random numbers.

There is no exercise file for this Tutorial.

The Math object

The JavaScript Math object offers lots of methods and properties for working with numbers. For example, rounding numbers, finding minimum and maximum values, and generating random numbers.

Syntax of the Math object

Unlike Date, another a built-in JavaScript object, the Math object is not a constructor and does not require the New keyword. Each Math object you use is automatically created by the JavaScript interpreter.

Below are some examples of code that uses the Math object.

${Math.round(9.75)}; // returns 10
${Math.max(1, 2, 3)};  // returns 3

Positive and negative numbers

JavaScript offers two methods for working with positive and negative numbers.

Math.abs(n)

Returns the absolute value of n.

Math.sign(n)

Returns 1 if n is positive, -1 if negative, or 0 if zero.

You can see some sample code below.

console.log(`Positive or negative number (19.99)? ${Math.sign(19.99)}`);
// returns 1
console.log(`Positive or negative number (-5)? ${Math.sign(-5)}`);
// returns -1
console.log(`Positive or negative number (0)? ${Math.sign(0)}`);
// returns 0

Integers and floats

Here are two common methods for working with integers and floats (floating-point numbers or decimals).

Math.round(n)

Returns the value of n rounded (up or down) to the nearest integer.

For example, 6.25 is rounded down to 6 and 7.75 becomes 8.

If n is a negative number, the return value is rounded upwards towards zero. -8.25 becomes -8.

Math.trunc(n)

Returns only the integer part of n.

All numbers after the decimal point . are discarded. No rounding is performed.

For example, 3.14159 simply returns 3.

Two related methods are the following.

Math.ceil(n)

Rounds n up to the next largest integer.

For example, 3.5 becomes 4, -5.7 becomes -5 (because -5 is greater than -6).

Math.floor(n)

Returns the largest integer less than or equal to n.

For example, 3.5 becomes 3, -5.7 becomes -6 (because -6 is lesser than -5).

You can see some sample code below.

console.log(Math.ceil(.95));    // returns 1
console.log(Math.ceil(4));      // returns 4
console.log(Math.ceil(7.004));  // returns 8
console.log(Math.ceil(-7.004)); // returns -7
console.log(Math.floor(45.95));  // returns 45
console.log(Math.floor(45.05));  // returns 45
console.log(Math.floor(4));      // returns 4
console.log(Math.floor(-45.05)); // returns -46
console.log(Math.floor(-45.95)); // returns -46

Note the difference between these two methods and Math.round(n):

  • Math.ceil(n): Rounds n upward towards the next integer value.   So 5.01 becomes 6 and 14.275 becomes 15.
  • Math.floor(n): Rounds n downward towards the next smallest integer value.   So 5.99 becomes 5 and 14.9999 becomes 14.
  • Math.round(n): Rounds n upward or downward to the nearest integer.   So 5.25 becomes 5 and 14.75 becomes 15.

These two methods are commonly used to transform the output of the Math.random() method from floats to more usable integer values.

Maximum and minimum values

For when you want to find the largest or smallest number in a range of numeric values, use one of the following methods.

Math.max(x,y,z)

Returns the highest number in a supplied range numeric parameters.

Math.min(x,y,z)

Returns the lowest number in a supplied range numeric parameters.

Here are some code samples.

console.log(Math.max(1, 2, 3));    // returns 3
console.log(Math.max(-1, -2, -3)); // returns: -1
console.log(Math.min(1, 2, 3));    // returns 1
console.log(Math.min(-1, -2, -3)); // returns -3

Generating random numbers

For when you want to generate a random value for a numeric variable, JavaScript offers the method below.

Math.random()

Returns a pseudo-random floating-point number in the range from 0 inclusive up to but not including 1.

Here is the code in its simplest form.

console.log(Math.random()); // returns a number from 0 to less than 1

Typcially, you will want your random number to be an integer rather than a floot. A simple solution is to:

  • Use the Math.floor() method to find the largest integer less than or equal to randomly-generated float.
  • Multply the output of the Math.floor() method by your choosen integer.

See the examples below.

console.log(Math.floor(Math.random() * 3)); 
// returns 0, 1 or 2 (never 3)
console.log(Math.floor(Math.random() * 6));
// returns 0, 1, 2, 4 or 5 (never 6)  

If you want a random integer between zero and one less than some supplied integer max, you could use the following solution:

// Function to generate random integer one less than supplied parameter
function getRandomIntUpper(max) {
   return Math.floor(Math.random() * max);
}
                 
console.log(getRandomIntUpper(5)); // returns: 0, 1, 2, 3 or 4
console.log(getRandomIntUpper(6)); // returns 0, 1, 2, 4 or 5 

The function below accepts as parameters two integers that will specify the smallest and largest possible random output inclusively.

// Generate random integer between supplied range inclusively
function getRandomInt(min, max) {
   min = Math.ceil(min);
   max = Math.floor(max);
   return Math.floor(Math.random() * (max - min + 1) + min); 
}

// Both the min and max arguments are inclusive
console.log(getRandomInt(1, 9));  // returns 1, 2, 3, 4, 5, 6, 7, 8 or 9
console.log(getRandomInt(20, 24));// returns 20, 21, 22, 23 or 24

 

 Back to Top