Math.round() / Math.floor() / Math.ceil()

Overview

Overviewvisual1

The Math.round() function accepts a number and returns its value rounded to the nearest integer:

Math.round(x);

The Math.floor() and Math.ceil() functions return the value of a number rounded down to the nearest integer and rounded up, respectively:

Math.floor(x);
Math.ceil(x);

The Math.round(), Math.floor(), and Math.ceil() functions are methods of the Math object, which has a set of functions that other programmers have defined for us to use. Here is a full list of available math functions.

Round a Number

In this example, we use the Math.round(), Math.floor(), and Math.ceil() functions to round a number assigned to the variable x.

var x = 8.3962; // Assign the number to round

var a = Math.round(x);
var b = Math.floor(x);
var c = Math.ceil(x);

Change the value assigned to the variable x to see how the Math.round(), Math.floor(), and Math.ceil() functions work. You can also assign the variable an arithmetic expression, such as 17 / 3 .

To learn more about variables, visit the Variables lesson.

Quick Reference: Variables

Editor (write code below)
var canvas = document.getElementById('round_example1'); var context = canvas.getContext('2d'); var x = 8.3962; // Assign the number to round var a = Math.round(x); var b = Math.floor(x); var c = Math.ceil(x); context.fillStyle = 'Black'; context.font = '16px Arial'; context.fillText(a + ' is ' + x + ' rounded to the nearest integer.', 20, 32); context.fillText(b + ' is ' + x + ' rounded down to the nearest integer.', 20, 64); context.fillText(c + ' is ' + x + ' rounded up to the nearest integer.', 20, 96);
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Round the Dimensions of a Rectangle

In this example, we use the Math.floor() and Math.ceil() functions to round the dimensions of a rectangle.

We start by assigning two decimal numbers to the variables a and b.

var a = 183.67;
var b = 107.44;

Then, we use the Math.floor() function to round a down to the nearest integer for the width of the rectangle and the Math.ceil() function to round b up to the nearest integer for the height.

var w = Math.floor(a);
var h = Math.ceil(b);

When drawing the rectangle using the context.fillRect() method, the rectangle has a width of 183 and a height of 108. Change the values assigned to the variables a and b to see how the dimensions of the rectangle change.

To learn more about drawing rectangles, visit the Coordinates and fillRect() lessons.

Quick Reference: Coordinates Variables fillRect() fillStyle

Editor (write code below)
var canvas = document.getElementById('round_example2'); var context = canvas.getContext('2d'); var a = 183.67; var b = 107.44; var w = Math.floor(a); var h = Math.ceil(b); context.fillStyle = 'MediumSeaGreen'; context.fillRect(100, 100, w, h); context.fillStyle = 'Black'; context.font = '16px Arial'; context.textAlign = 'center'; context.textBaseline = 'middle'; context.fillText(w + ' x ' + h, 100 + w / 2, 100 + h / 2);
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Challenge 1

Challenge1visual1
What your drawing should look like

Calculate the width of the rectangle by rounding the value of the variable a up to the nearest integer and calculate the height by rounding the value of the variable b also up to the nearest integer.

Editor (write code below)
var canvas = document.getElementById('round_challenge1'); var context = canvas.getContext('2d'); var a = 90 * Math.PI; var b = 1.6 * Math.exp(5); var w; // Round the value of a up to the nearest integer var h; // Round the value of b up to the nearest integer context.fillStyle = 'Orchid'; context.fillRect(40, 40, w, h);
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)
Challenge1

Calculate a Color

When describing a color, RGB values must be whole numbers between 0 and 255.

In this example, we describe one color using RGB values assigned to the variables r1, g1, and b1 and a second color using RGB values assigned to the variables r2, g2, and b2.

var r1 = 255; // RGB values for color 1
var g1 = 0;
var b1 = 0;

var r2 = 0; // RGB values for color 2
var g2 = 102;
var b2 = 255;

We then mix the two colors to create three in-between colors. To create a color that is 75% color 1 and 25% color 2, we multiply the RGB values of color 1 by 0.75 and the RGB values of color 2 by 0.25 and add them together. In case some of the calculated RGB values for the new colors are decimals and not whole numbers, we use the Math.round() function to round them.

The expression to calculate the red component of a color that is 75% color 1 and 25% color 2 looks like this:

Math.round(0.75 * r1 + 0.25 * r2) // Red component of the mixed color

Finally, we draw five rectangles. The rectangle on the left is filled with color 1. The rectangle on the right is filled with color 2. The three rectangles in the middle are filled with the three in-between colors. Change the RGB values for color 1 and color 2 to see what happens.

To learn more about defining fill colors, visit the fillStyle lesson.

Quick Reference: Coordinates Variables fillRect() fillStyle

Editor (write code below)
var canvas = document.getElementById('round_example3'); var context = canvas.getContext('2d'); var r1 = 255; // RGB values for color 1 var g1 = 0; var b1 = 0; var r2 = 0; // RGB values for color 2 var g2 = 102; var b2 = 255; context.fillStyle = 'rgb(' + r1 + ', ' + g1 + ', ' + b1 + ')'; // Color 1 context.fillRect(10, 10, 70, 280); context.fillStyle = 'rgb(' + Math.round(0.75 * r1 + 0.25 * r2) + ', ' + Math.round(0.75 * g1 + 0.25 * g2) + ', ' + Math.round(0.75 * b1 + 0.25 * b2) + ')'; // 75% color 1, 25% color 2 context.fillRect(80, 10, 70, 280); context.fillStyle = 'rgb(' + Math.round(0.5 * r1 + 0.5 * r2) + ', ' + Math.round(0.5 * g1 + 0.5 * g2) + ', ' + Math.round(0.5 * b1 + 0.5 * b2) + ')'; // 50% color 1, 50% color 2 context.fillRect(150, 10, 70, 280); context.fillStyle = 'rgb(' + Math.round(0.25 * r1 + 0.75 * r2) + ', ' + Math.round(0.25 * g1 + 0.75 * g2) + ', ' + Math.round(0.25 * b1 + 0.75 * b2) + ')'; // 25% color 1, 75% color 2 context.fillRect(220, 10, 70, 280); context.fillStyle = 'rgb(' + r2 + ', ' + g2 + ', ' + b2 + ')'; // Color 2 context.fillRect(290, 10, 70, 280);
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Challenge 2

Challenge2visual1
What your drawing should look like

The program below draws four rectangles and fills them with the color from the RGB values assigned to the variables r, g, and b.

Update the program so the second rectangle is filled with a color created by multiplying the RGB values in the variables r, g, andbby 0.75; the third rectangle is filled with a color created by multiplying the RGB values by 0.5; and the fourth rectangle is filled with a color created by multiplying the RGB values by 0.25. Make sure to round the calculated RGB values for the new colors so they are whole numbers.

Editor (write code below)
var canvas = document.getElementById('round_challenge2'); var context = canvas.getContext('2d'); var r = 255; // RGB values for the color var g = 165; var b = 0; context.fillStyle = 'rgb(' + r + ', ' + g + ', ' + b + ')'; context.fillRect(10, 10, 90, 280); context.fillRect(100, 10, 90, 280); context.fillRect(190, 10, 90, 280); context.fillRect(280, 10, 90, 280);
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)
Challenge2

Snap a Rectangle to a Grid

In this example, we use the Math.round() function to snap a rectangle to a grid.

We are registering an anonymous function to listen for mousemove events on the canvas. If the mouse is moved over the canvas, a mousemove event is generated and passed into the anonymous function, where it is then stored in the parameter e.

canvas.addEventListener('mousemove', function(e) {
  
  // Code block
  
});

As the mouse moves over the canvas, we can access the mouse's coordinates on the canvas through the mousemove event's layerX and layerY properties. By setting the width of the rectangle to the value of layerX and the height to the value of layerY, we can resize the rectangle so it's bottom left corner moves with the mouse. However, we don't want the size of the rectangle to change freely as the mouse moves. We want the rectangle to snap to the grid below.

The lines on the grid are 40 pixels apart. So, to keep the rectangle aligned to the grid, the dimensions of the rectangle must be multiples of 40. We are using the Math.round() function to round the width and height of the rectangle to the nearest multiple of 40:

canvas.addEventListener('mousemove', function(e) {
  var w = 40 * Math.round(e.layerX / 40);
  var h = 40 * Math.round(e.layerY / 40);
});

Let's say the mouse's coordinates on the canvas are (190, 85). If we divide 190 by 40 and round the answer, we get 5. This means 40 goes into 190 about 5 times. Multiplying 40 by 5 then gives us 200, a multiple of 40, for the width of the rectangle. If we divide 85 by 40 and round the answer, we get 2. This means 40 goes into 85 about 2 times. Multiplying 40 by 2 then gives us 80, another multiple of 40, for the height of the rectangle. Because the dimensions of the rectangle are multiples of 40, it snaps to the grid below.

To learn more about handling events, visit the addEventListener() lesson.

Quick Reference: Coordinates Variables Functions fillRect() save() / restore() lineTo()

Editor (write code below)
var canvas = document.getElementById('round_example4'); var context = canvas.getContext('2d'); canvas.addEventListener('mousemove', function(e) { var w = 40 * Math.round(e.layerX / 40); var h = 40 * Math.round(e.layerY / 40); context.save(); context.clearRect(0, 0, canvas.width, canvas.height); drawGrid(); context.fillStyle = 'rgba(30, 144, 255, 0.6)'; context.fillRect(0, 0, w, h); context.restore(); }); drawGrid(); function drawGrid() { var w = 40 * Math.ceil(canvas.width / 40); var h = 40 * Math.ceil(canvas.height / 40); context.save(); context.strokeStyle = '#999999'; for (var i = 0; i <= w; i += 40) { context.beginPath(); context.moveTo(i, 0); context.lineTo(i, h); context.stroke(); } for (var j = 0; j <= h; j += 40) { context.beginPath(); context.moveTo(0, j); context.lineTo(w, j); context.stroke(); } context.restore(); }
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Challenge 3

Challenge3visual1
What your drawing should look like

Calculate the width of the rectangle by rounding the value of the variable a to the nearest multiple of 50 and calculate the height by rounding the value of the variable b to the nearest multiple of 30.

Editor (write code below)
var canvas = document.getElementById('round_challenge3'); var context = canvas.getContext('2d'); var a = 90 * Math.PI; var b = 1.6 * Math.exp(5); var w; // Round the value of a to the nearest multiple of 50 var h; // Round the value of b to the nearest multiple of 30 context.fillStyle = 'OrangeRed'; context.fillRect(50, 30, w, h); if (w > 0 && w % 50 == 0 && h > 0 && h % 30 == 0) { context.fillStyle = 'Black'; context.font = '16px Arial'; context.textAlign = 'center'; context.textBaseline = 'middle'; context.fillText(w + ' x ' + h, 50 + w / 2, 30 + h / 2); }
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)
Challenge3

Ready for the next lesson?

Next up, the "setInterval()" lesson >