Using The Math.ceil() Function In Javascript To Round a Number Up

Published on | by
Reza Baharvand
Updated on
Image for Using The Math.ceil() Function In Javascript To Round a Number Up

Introduction

To round a number up in Javascript, you can use the Math.ceil() function.

This function accepts a number as an argument, rounds it up, and then returns that number.

Using Math.ceil()

You can write a function to take a number and return the smallest integer greater than or equal to the input:

function ceilNumber(num) { let ceil = Math.ceil(num); console.log(ceil); }

This function applies the Math.ceil() and logs the result.

You can see this in action below:

ceilNumber(5); // 5 ceilNumber(5.001); // 6 ceilNumber(5.999); // 6

Math.ceil() vs Math.floor()

The Math.floor() function, unlike the Math.ceil() method, round the number down.

console.log(Math.ceil(5.999)); // 6 console.log(Math.floor(5.999)); // 5

You can learn more about it on Math.floor() Function in Javascript, Uses, Limitations, Type Coercion.


Recent Posts

Image for Coin Flip Simulator With Javascript And CSS Animations

Coin Flip Simulator With Javascript And CSS Animations

In this tutorial, you will learn to build a small app to toss a coin using HTML, CSS, and Javascript. The possible outcomes after flipping a coin are either "Head" or "tail". The probability of getting head or tail is 50%.

Image for Use Math.PI To Calculate Area And Circumference Of A Circle

Use Math.PI To Calculate Area And Circumference Of A Circle

The "Math.PI" property returns the PI "π" constant, approximately equal to 3.14159. For example, you can calculate the circumference and surface area of a circle using "Math.PI".

Image for Check If A Function Exists Before Calling With The typeof Operator

Check If A Function Exists Before Calling With The typeof Operator

If you are sharing scripts from different modules or you have a large codebase, you can use the `typeof` operator to check if a function exists.

Image for Create A Toggle Button In Javascript To Manipulate The DOM With The toggle() Method

Create A Toggle Button In Javascript To Manipulate The DOM With The toggle() Method

The "toggle()" is a method of the "DOMTokenList". It removes something like a "class" name from the list, and returns "false". If the "class" name does not exist, it will add it to the list and return "true".