Math.round() function only rounds numbers up or down to whole numbers.
It’s important to understand that
Math.round() only rounds to the nearest integer value. But, by understanding that we can use some simple math to allow us to round to 2 decimal places.
All you need to do is to multiply the number you want to round by 100 and then divide by 100. Let’s look at an example below.
In the example above, we take the number
This method can also be used to round a number to any number of decimal places. You simply need to add a zero to the number you are multiplying by and dividing by to increase the number of decimal places you want to show. See the example below.
tofixed() works, is it returns a string of the number that has exactly the number of decimal places you specify. Let’s look at an example to see how it works.
As you can see in the example above, by giving the
toFixed() method an argument of 2 it will return a the number as a string rounded to 2 decimal places with the value of ‘123.46″. Now before we look at how to convert it back to a number we need to understand this method some more.
It is important to understand that if the number of decimals you pass as an argument is greater than what the number will show it will pad it with zero’s. Let’s look at a quick example.
Now, let’s quickly look at how to convert the string back to a number.
Above we use a unary plus (
+), that is a plus symbol that goes before the value. What it does is attempts to convert the object into a number. As a result, our value will be outputted with the
I would not recommend doing this as it is bad for performance. It is more just a proof of concept that it can be done.
What do you expect the below output to be?
If you said
1.25. What the hell? What is going on?
The above function avoids the rounding errors mentioned by using numbers that are represented as exponentials. You could even convert it to a function that rounds to any number you specify.
Did You Enjoy This?
Then consider following me on Twitter or if you’re a curious like me, why not be one of the first people to join my newsletter. I’ll help you level up your coding skills.