I am trying to do this but is all I have found is rounding to the nearest whole number. I was wondering if there was a way to do this with math.round or if there is a different solution. Thanks!
Method 1: The quick way is to use toFixed()
method like this:
var num = 2.12;
var round = num.toFixed(1); // will out put 2.1 of type String
One thing to note here is that it would round 2.12
to 2.1
and 2.15
to 2.2
Method 2: On the other hand you can use Math.round
with this trick:
var num = 2.15;
Math.round(num * 10) / 10; // would out put 2.2
It would round to the upper bound.
So, choose whichever you like.
Also if you use a modern version of JS ie. ES then using const
and let
instead for variable declaration might be a better approach.
NOTE: remember that .toFixed() returns a string. If you want a number, use the Math.round() approach. Thanks for the reminder @pandubear
Math.round(X); // round X to an integer
Math.round(10*X)/10; // round X to tenths
Math.round(100*X)/100; // round X to hundredths
Math.round(1000*X)/1000; // round X to thousandths
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With