Remove the Digits after the Decimal in JavaScript


Borislav Hadzhiev

Last updated: Oct 25, 2021


Photo from Unsplash

Remove the Digits after the Decimal #

Use the Math.trunc() function to remove the digits after the decimal, e.g. Math.trunc(1.37). The Math.trunc() function removes the fractional digits and returns the integer part of the number.

const num = 123.567; const removeDecimal = Math.trunc(num); // 👉️ 123 console.log(removeDecimal); const roundDown = Math.floor(num); // 👉️ 123 console.log(roundDown); const roundNearestInteger = Math.round(num); // 👉️ 124 console.log(roundNearestInteger); const roundUp = Math.ceil(num); console.log(roundUp); // 👉️ 124

Our first example uses the Math.trunc function.

The function doesn't round the number in any way, it simply truncates the decimal part and returns the integer.

Here are some examples:

console.log(Math.trunc(-1.37)); // 👉️ -1 console.log(Math.trunc(2.0)); // 👉️ 2 console.log(Math.trunc(5.35)); // 👉️ 5

The next possible scenario is to remove the digits after the decimal, by rounding down. To achieve this, use the Math.floor function.

The function returns the largest integer that is less than or equal to the supplied number. Here are some examples.

console.log(Math.floor(-1.37)); // 👉️ -2 console.log(Math.floor(2.6)); // 👉️ 2 console.log(Math.floor(5.35)); // 👉️ 5

The next example shows how to round numbers to the nearest integer using the Math.round function. Here are some examples.

console.log(Math.round(-1.37)); // 👉️ -1 console.log(Math.round(2.5)); // 👉️ 3 console.log(Math.round(5.49)); // 👉️ 5

The last example shows how to remove the digits after the decimal by rounding up, using the Math.ceil function.

The Math.ceil function always rounds a number up. Here are some examples.

console.log(Math.ceil(-1.99)); // 👉️ -1 console.log(Math.ceil(2.01)); // 👉️ 3 console.log(Math.ceil(5.49)); // 👉️ 6
If you want to simply remove the digits after the decimal, without rounding in any way, use the Math.trunc function.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.