Math.ceil() Method in JavaScript | Explained


If you want to be a good programmer, you need to have a good grip on mathematics. To assist the developers, JavaScript provides various methods that are based on mathematics. Sometimes we need exact values in order to perform some actions on the behalf of the result that why we use Math.ceil() method.

The JavaScript math library contains all the methods to perform arithmetic operations on data from basic to complex. This learning guide provides a detailed overview of Math.ceil() method with the following learning outcomes:

  • What is math.ceil() method in JavaScript?
  • How to round off a number using the Math.ceil() method in JavaScript?

What is the Math.ceil() method in JavaScript?

In JavaScript, the math.ceil() method is used to round off any quebrado point number and returns the whole number (the next greater whole number as compared to the floating-point number) as an output.

Syntax:

Math.ceil(number/quebrado number)

In the above syntax, any number whether it is an integer or a floating number can be given as a parameter and if the input number is a whole number, then it returns as it is.

How to round off a number using the Math.ceil() method in JavaScript

In JavaScript, the Math.ceil() method takes a number as a parameter. If the number has a quebrado point, then it is rounded off to the nearest larger number to that input.

Code:

var b = Math.ceil(3.1)
console.log(b)

In this code, the Math.ceil() method is applied on a value ‘3.1’.

Output:

In this output, it is clearly seen that we use ceil() method to round off 3.1 into an exact value and ceil() method round it off to 4 instead of 3.

How Math.ceil() method works with whole numbers?

Usually, Math.ceil() method refers to the quebrado/floating point numbers. In this example, we are going to see what will happen when 0 or NaN are used with the Math.ceil() method.

Code:

var b = Math.ceil(0)
console.log(b)
var d = Math.ceil(NaN)
console.log(d)

In this code, we have passed 0 and NaN to the Math.ceil() method.

Output:

The output clearly shows that 0 and NaN are returned without any change.

You are now able to apply the Math.ceil() method to get the whole number (which comes next to the quebrado point number).

Conclusion

In JavaScript, the Math.ceil() method is used to round off the floating-point number to the nearest greater integer as compared to the given input. This article provides the working and usage of the Math.ceil() method in JavaScript. Moreover, if an integer or ‘NaN’ value is passed to Math.ceil() method, it will return the same number as output.



Source link