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!
Asked
Active
Viewed 2.4k times
16
-
please add some more use cases and what you have tried. – Nina Scholz Jul 16 '18 at 08:14
-
3Possible duplicate of [Round to at most 2 decimal places (only if necessary)](https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary) – Rawling Jul 16 '18 at 08:15
-
I have looked around quite a bit and not found anything, the link that you sent dosn't work in my case because i want it rounded to the tenth, not 100th. – Tech Hax Jul 16 '18 at 08:20
-
@TechHax _“because I want it rounded to the tenth, not 100th”_ — but hopefully you understand the solutions given in the answers and can easily adjust them, right? We don’t need a new question for every possible rounding. – Sebastian Simon Jul 16 '18 at 08:26
-
Possible duplicate of [How do you round to 1 decimal place in Javascript?](https://stackoverflow.com/questions/7342957/how-do-you-round-to-1-decimal-place-in-javascript) – Sebastian Simon Jul 16 '18 at 08:28
2 Answers
31
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

tmw
- 1,424
- 1
- 15
- 26
-
1_“One thing to note here that it would round `2.15` to `2.1` and `2.15` to `2.2`.”_ — only at most one of these is true. You probably also want to explain why this is; there exist [different rounding methods](https://stackoverflow.com/q/977796/4642212). – Sebastian Simon Jul 16 '18 at 08:30
-
1Worth warning that .toFixed() returns a string. If you want a number, use the Math.round() approach. – Pandu Jun 14 '21 at 17:41
6
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

Nelson_Frank
- 101
- 1
- 3
-
Hope It will solve issue but please add explanation of your code with it so user will get perfect understanding which he/she really wants. – Jaimil Patel Jun 01 '20 at 04:59