你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
当前回答
完成最佳答案:
var round = function ( number, precision )
{
precision = precision || 0;
return parseFloat( parseFloat( number ).toFixed( precision ) );
}
输入参数number可能"not"总是一个数字,在这种情况下。tofixed不存在。
其他回答
var number = 123.456;
console.log(number.toFixed(1)); // should round to 123.5
var num = 34.7654;
num = Math.round(num * 10) / 10;
console.log(num); // Logs: 34.8
function rnd(v,n=2) {
return Math.round((v+Number.EPSILON)*Math.pow(10,n))/Math.pow(10,n)
}
这个很好地抓住了极端情况
Math.round( mul/count * 10 ) / 10
Math.round(Math.sqrt(sqD/y) * 10 ) / 10
谢谢
Lodash有一个循环方法:
_.round(4.006);
// => 4
_.round(4.006, 2);
// => 4.01
_.round(4060, -2);
// => 4100
文档。
源。