Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I round a number (eg: 2.12) to the nearest tenth (2.1) in JS

Tags:

javascript

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!

like image 485
Tech Hax Avatar asked Jul 16 '18 08:07

Tech Hax


2 Answers

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

like image 70
tmw Avatar answered Sep 21 '22 18:09

tmw


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
like image 37
Nelson_Frank Avatar answered Sep 20 '22 18:09

Nelson_Frank