Math.round(x)
Category:Math
Some apps need to know how to round a number to the nearest integer. The tie-breaking rule for half-way numbers (ending in ".5") is to round them up to the next largest integer.
Examples
Example: Typical Usage
var x = Math.round(15.2);
console.log(x);
var y = Math.round(23.5);
console.log(y);
var z = Math.round(-7.8);
console.log(z);
Example: Floor
Uses arithmetic and round() to round a number down to the next smallest integer.
// Uses arithmetic and round() to round a number down to the next smallest integer.
function floor(n) {
return Math.round(n-0.5);
}
console.log(floor(24.8));
console.log(floor(-23.5));
Syntax
Math.round(x);
Parameters
Name | Type | Required? | Description |
---|---|---|---|
x | number | An arbitrary number or variable. |
Returns
A number representing the integer nearest to x, or NaN if x is not a number or no parameter is provided.
Found a bug in the documentation? Let us know at support@code.org.