Javascript

How to remove decimals in JavaScript?

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

Written by Luci · 1 min read >

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"

Be aware that toFixed() returns a String, not a Number.

If you want to keep it as number but with decimals you’ll have to do:

parseFloat(decimal.toFixed(1));
// returns 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.

Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x