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.
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;
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.
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.
As hinted in the name,
Math.round() will return a number rounded up to the nearest integer.
const removedDecimal = Math.round(decimal); // returns 5
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.