你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
当前回答
Lodash有一个循环方法:
_.round(4.006);
// => 4
_.round(4.006, 2);
// => 4.01
_.round(4060, -2);
// => 4100
文档。
源。
其他回答
我做了一个返回数字类型,也只在需要的时候放置小数(没有0填充)。
例子:
roundWithMaxPrecision(11.234, 2); //11.23
roundWithMaxPrecision(11.234, 1); //11.2
roundWithMaxPrecision(11.234, 4); //11.23
roundWithMaxPrecision(11.234, -1); //10
roundWithMaxPrecision(4.2, 2); //4.2
roundWithMaxPrecision(4.88, 1); //4.9
代码:
function roundWithMaxPrecision (n, precision) {
const precisionWithPow10 = Math.pow(10, precision);
return Math.round(n * precisionWithPow10) / precisionWithPow10;
}
这似乎对我抛出的任何东西都有效:
function round(val, multiplesOf) {
var s = 1 / multiplesOf;
var res = Math.ceil(val*s)/s;
res = res < val ? res + multiplesOf: res;
var afterZero = multiplesOf.toString().split(".")[1];
return parseFloat(res.toFixed(afterZero ? afterZero.length : 0));
}
它是四舍五入的,所以您可能需要根据用例修改它。这应该可以工作:
console.log(round(10.01, 1)); //outputs 11
console.log(round(10.01, 0.1)); //outputs 10.1
使用toprecprecision方法:
var a = 1.2345
a.toPrecision(2)
// result "1.2"
数学。整数(num * 10) / 10无效。
例如,1455581777.8-145558160.4会得到1310023617.3999999。
所以只使用num。tofixed (1)
如果你的方法不起作用,请发布你的代码。
然而,你可以完成舍入任务如下:
var value = Math.round(234.567*100)/100
234.56英镑可以吗
类似的
var value = Math.round(234.567*10)/10
会给出234.5
通过这种方式,您可以使用一个变量来代替前面使用的常量。