Sunday, April 20, 2025

Understanding Math.ceil() in JavaScript

   

When working with numbers in JavaScript, especially decimal values, sometimes you need to round them up to the nearest whole number. That’s where the Math.ceil() method comes in handy.

What is Math.ceil()?

The Math.ceil() method returns the smallest integer greater than or equal to a given number. In simple terms, it always rounds a number up, regardless of whether it's positive or negative.

Syntax:

Math.ceil(number)

Example:

Let’s explore how Math.ceil() works with both positive and negative decimal values:

<script>
    var one = Math.ceil(6.9);
    document.writeln('Output of 6.9 is : ' + one + '<br><br>');

    var two = Math.ceil(30.4);
    document.writeln('Output of 30.4 is : ' + two + '<br><br>');

    var three = Math.ceil(-40.9);
    document.writeln('Output of -40.9 is : ' + three + '<br><br>');

    var four = Math.ceil(-8.8);
    document.writeln('Output of -8.8 is : ' + four + '<br><br>');
</script>

Output:

Output of 6.9 is : 7  
Output of 30.4 is : 31  
Output of -40.9 is : -40  
Output of -8.8 is : -8  

How it Works:

Math.ceil(6.9) ➝ rounds up to 7

Math.ceil(30.4) ➝ rounds up to 31

Math.ceil(-40.9) ➝ rounds up to -40 (yes, it's still "up" in the negative direction)

Math.ceil(-8.8) ➝ rounds up to -8

Key Points:

Math.ceil() always rounds upward to the nearest integer.

It works with both positive and negative numbers.

It's useful when you need to ensure the result is not less than the original value.

No comments:

Post a Comment