What is the difference between Math.ceil() and Math.round() methods in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

Math.ceil() and Math.round() methods differ in a way that the former round off a number to its nearest integer in upward direction of rounding(towards the greater value) whereas the latter round off a number to its nearest integer in downward direction of rounding(towards lower value). Let's examine the two methods individually.

Math.ceil()

Math.ceil() method round off number passed as parameter to its nearest integer so as to get greater value.

Example

In the below example when a number 5.34 passed as a parameter, Math.ceil() round off it in to 6, which is a greater value than actual number.

Live Demo

<html>
<body>
<script>
   document.write(Math.ceil(5.34));
</script>
</body>
</html>

Output

6

Math.round()

Math.round() method round off number passed as parameter to its nearest integer so as to get lower value.

Example

In the below example when a number 5.34 passed as a parameter, Math.round() round off it in to 5, which is a lower value than actual number.

Live Demo

<html>
<body>
<script>
   document.write(Math.round(5.34));
</script>
</body>
</html>

Output

5
raja
Published on 29-May-2019 15:14:32
Advertisements