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:
Math.round()
to round to the nearest integer.parseInt()
to parse to the nearest whole number.Math.trunc()
to completely strip the decimal.toFixed()
to remove a certain amount of decimals.
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.