你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?

我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。


当前回答

Lodash有一个循环方法:

_.round(4.006);
// => 4

_.round(4.006, 2);
// => 4.01

_.round(4060, -2);
// => 4100

文档。

源。

其他回答

如果你的方法不起作用,请发布你的代码。

然而,你可以完成舍入任务如下:

var value = Math.round(234.567*100)/100

234.56英镑可以吗

类似的

 var value = Math.round(234.567*10)/10

会给出234.5

通过这种方式,您可以使用一个变量来代替前面使用的常量。

你可以简单地做以下几点:

let n = 1.25
let result = Number(n).toFixed(1)
// output string: 1.3

我找到了一个避免精度问题的方法:

function badRound (num, precision) {
    const x = 10 ** precision;
    return Math.round(num * x) / x
}
// badRound(1.005, 2) --> 1

function round (num, precision) {
    const x = 10 ** (precision + 1);
    const y = 10 ** precision;
    return Math.round(Math.round(num * x) / 10) / y
}
// round(1.005, 2) --> 1.01
var num = 34.7654;

num = Math.round(num * 10) / 10;

console.log(num); // Logs: 34.8

数学。整数(num * 10) / 10无效。

例如,1455581777.8-145558160.4会得到1310023617.3999999。

所以只使用num。tofixed (1)