Table of Contents
Rounding numbers can be a little frustrating if you don’t know the right method or approach to use for it. You might want to round down your number value, and so the static
round method would not suffice.
With the built-in
Math object, we can carry out many mathematical operations and rounding is one such. The first method that comes to mind when the idea of rounding numbers is present is the
Method-1: Using the
Math.round() method rounds its number value argument to the nearest integer based on typical mathematical rounding. So, if the decimal point of the number is greater than or equal to 0.5, it rounds up to the next higher absolute value, but if is lower than 0.5, it rounds down to the lower absolute value. For example, if the number we have is
4.6, it will round up to
5, but if the number is
4.3, it will round down to
const num = 4.56; const numRounded = Math.round(num); console.log(numRounded);
However, if we need a case where the decimal point of the number is greater than 0.5 or less than 0.5, it should always round down, we need another method, and that’s where the
trunc method comes in.
Method-2: Using the
floor method is also a static method within the
Math object, and it rounds down the number value passed to it. So, if you pass 4.99 to the
floor method, it would return
4. Let’s show the
floor method in action.
const num = 4.98; const numRounded = Math.floor(num); console.log(numRounded);
Math.floor() method, you can round down the number value.
Method-3: Round down using the
If you want another static
Math method, we make use of the
trunc method returns only the integer part of a number (as it removes the decimal number). It works by simply splitting the number from the point of the
dot, and return the left side (the integer part).
To illustrate we will use the
Math.trunc() method on a whole number and a decimal value.
const numOne = 4.98; const numTwo = 17; const numOneRound = Math.floor(numOne); const numTwoRound = Math.floor(numTwo); console.log(numOneRound, numTwoRound);
So, with the
4.98, it was round down to
4, and the number
17 was left as it is.
Math method -
trunc - which work in different ways but achieve the set goal.