我如何将数字(例如:2.12)四舍五入到 JS 中最接近的十分之一(2.1)

Tec*_*Hax 7 javascript

我正在尝试这样做,但我发现的只是四舍五入到最接近的整数。我想知道是否有办法用 math.round 来做到这一点,或者是否有不同的解决方案。谢谢!

tah*_*eer 16

方法1:快速的方法是使用这样的toFixed()方法:

var num = 2.12;
var round = num.toFixed(1); // will out put 2.1 of type String
Run Code Online (Sandbox Code Playgroud)

这里有一点要注意的是,它会四舍五入2.122.12.152.2

方法 2:另一方面,您可以使用Math.round此技巧:

var num = 2.15;
Math.round(num * 10) / 10; // would out put 2.2
Run Code Online (Sandbox Code Playgroud)

它会四舍五入到上限。

所以,选择你喜欢的。

此外,如果您使用现代版本的 JS,即。ES 然后使用constandlet代替变量声明可能是更好的方法。

注意:记住 .toFixed() 返回一个字符串。如果您想要一个数字,请使用 Math.round() 方法。感谢提醒@pandubear


小智 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
Run Code Online (Sandbox Code Playgroud)