Site icon codippa

Javascript Math.round()

Javascript round number
In this article, we will understand how to round a decimal to its nearest integer in javascript using its Math.round() function with examples.
Math.round()
Javascript Math object has a round() function which accepts a decimal number as argument and rounds it off to the nearest integer as per the following rules.

So, -2.3, -5.4, -1.2 will be rounded off to -2, -5 and -1 respectively.
-2.6, -5.7, -1.8 will be rounded off to -3, -6 and -2 respectively, and
-8.5, -23.5, -45.5 will be rounded to -8, -23 and -45(Note this).
Syntax
round() is a static method of Math object and so, you don’t need create a javascript object to call it.
Following is the syntax of round() function

Math.round(number)

where, number is the decimal value to be rounded.
Examples
Below are some of the examples of Math.round()

let num1 = Math.round(89.5)
console.log(num1);
let num2 = Math.round(33.2)
console.log(num2);
let num3 = Math.round(21.2999)
console.log(num3);
console.log('--- Rounding negative numbers ---);
let num4 = Math.round(-12.7)
console.log(num4);
let num5 = Math.round(-2.05)
console.log(num5);
// notice this
let num6 = Math.round(-54.5)
console.log(num6);

This is the output

90
33
21
— Rounding negative numbers —
-13
-2
-54

Passing string argument
round() function may be provided a string as an argument. It will return the same result if the string is parseable or convertible to a number, such as ’34’, ‘67.4’ etc.
If the string is not convertible to numeric format, then round() will return NaN. Example,

console.log(Math.round('23.4'));
console.log(Math.round('-12.5'));
console.log(Math.round('one'));

Output will be

23
-12
NaN

Browser support
round() function is supported by all the browsers. Following is a table of round() compatibility with different browser versions.

Browser Version
Chrome 1
Firefox 1
IE 3
Edge 12
Safari 1
Opera 3

Hope the article was useful.

Exit mobile version