How to remove decimal places in JavaScript? – 4 Easy Methods

When using integers with decimal places in our web applications we often want to change the format of them to display them better in our user interfaces.

There many different use cases for this. I’ve comes across this frequently when dealing with data visualization, where I want to display whole numbers on our graphs axes.

So, how can you remove decimal places in JavaScript? To remove decimal places in JavaScript we can use the following methods:

To demonstrate, let’s have a variable with a decimal number like so:

const decimal = 5.67567;

Using Math.trunc()

Math.trunc() will remove any fractional digits:

const removedDecimal = Math.trunc(decimal);
// returns 5

This is the easiest way to outright strip the integer of its decimals.

Using parseInt()

Without a second parameter, parseInt() will round up the number for us:

const removedDecimal = parseInt(decimal);
// returns 5

Please note, if looking for performance this is the slowest method.

Math.round()

As hinted in the name, Math.round() will return a number rounded up to the nearest integer.

const removedDecimal = Math.round(decimal);
// returns 5

Using toFixed()

The method toFixed() comes in handy when we want to remove only some of the decimal places:

decimal.toFixed();
// return 6

decimal.toFixed(2)
// returns 5.68

decimal.toFixed(1)
// return 5.7

And there we have it, removing decimals comes into play more than you might think. Thankfully, we can see that there are many different approaches to solve it.

Proudly published with Gatsby