When working with decimal numbers or doubles in JavaScript, you might want to round them. To be able to do that, JavaScript has some functions to do that for you.
Rounding
The usual round is rounding a number up if it’s fraction is bigger than or equal to 0.5
, otherwise the number will be rounded down to the nearest integer.
1
2
let randomNumber = Math.round(1.42);
console.log(randomNumber);
As you can see we have to prefix the round
command with Math
which stands for the math package of JavaScript.
Rounding up
Rounding up is called ceil
and it comes from rounding to the ceiling. Every number will automatically be rounded up to the nearest integer.
1
2
let randomNumber = Math.ceil(1.42);
console.log(randomNumber);
Rounding down
Rounding down is called floor
and it comes from rounding to the floor. Every number will automatically be rounded down to the nearest integer.
1
2
let randomNumber = Math.floor(1.8);
console.log(randomNumber);