简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM