I'd like to round at most 2 decimal places, but only if necessary.
Input:
10
1.7777777
9.1
Output:
10
1.78
9.1
How can I do this in JavaScript
?
I'd like to round at most 2 decimal places, but only if necessary.
Input:
10
1.7777777
9.1
Output:
10
1.78
9.1
How can I do this in JavaScript
?
One can use
.toFixed(NumberOfDecimalPlaces)
.One way to achieve such a rounding only if necessary is to use Number.prototype.toLocaleString():
This will provide exactly the output you expect, but as strings. You can still convert those back to numbers if that's not the data type you expect.
This may help you:
for more information, you can have a look at this link
Math.round(num) vs num.toFixed(0) and browser inconsistencies
None of the answers found here is correct. @stinkycheeseman asked to round up, you all rounded the number.
To round up, use this:
2017
Just use native code
.toFixed()
If you need to be strict and add digits just if needed it can use
replace
Here is a simple way to do it:
You might want to go ahead and make a separate function to do it for you though:
Then you would simply pass in the value.
You could enhance it to round to any arbitrary number of decimals by adding a second parameter.