Number Rounding in JavaScript

The Number rounding is used in the math object. It is used to round up the given value to its nearest value. For example, consider a decimal number 4.6 then this number can be rounded up as 5, if the value after the decimal point is less than 5 then it would be round up as 4 and the value more than .5 is round up as 5.

JavaScript Number Round Syntax

var x= Math.round(“x”)

JavaScript Number Round Example

<!DOCTYPE html>
<title>Number Rounding in JavaScript</title>
	<script type="text/javascript">
		document.write("Actual Number: 4.4 <br>");
		x = Math.round(4.4);

		document.write("Rounded value: " + x + "<br>");

		y = Math.round(-7.8);
		document.write("Rounded value: " + y + "<br>");

		x = Math.round((2.11 * 10) / 10);
		document.write("Rounded value: " + x + "<br>");

		y = Math.round(1 ^ 4);
		document.write("Rounded value: " + y + "<br>");

		y = Math.round(5 / 2 * 10);
		document.write("Rounded value: " + y + "<br>");

  • This program is used for round up the given number to its nearest value.
  • In this program we have used various values that is positive and negative value and
    also have written few more values which have been rounded up by using math.round( ) method.
  • x = Math.round(4.7); is used to round up the number to the nearest integer.
  • y = Math.round(-7.2); is used to round up the negative value to its nearest integer.
  • In same manner we have taken few more method of math.round as we can see in the example,
    we get final rounded values after multiplying and dividing the values written in math.round() method.

Example Demo

  • Save the file as number_round.html in your system.
  • Just open the file in the browser, you will see the below picture in the browser.

When the execution process is completed successfully we will get the following output :

JavaScript - Number Rounding Example



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.