Remove the Digits after the Decimal in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 25 20211 min read

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.

index.js
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:

index.js
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.

index.js
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.

index.js
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.

index.js
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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee