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

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


当前回答

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

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

试试这个:

var original=28.453

// 1.- round "original" to two decimals
var result = Math.round (original * 100) / 100  //returns 28.45

// 2.- round "original" to 1 decimal
var result = Math.round (original * 10) / 10  //returns 28.5

// 3.- round 8.111111 to 3 decimals
var result = Math.round (8.111111 * 1000) / 1000  //returns 8.111

不那么复杂,更容易实现……

有了这个,你可以创建一个函数来做:

function RoundAndFix (n, d) {
    var m = Math.pow (10, d);
    return Math.round (n * m) / m;
}

函数RoundAndFix (n, d) { var m =数学。Pow (10, d); 返回数学。圆(n * m) / m; } console.log (RoundAndFix(8.111111, 3));

编辑:看这个如何四舍五入使用四舍五入一半。四舍五入模式是我们大多数人在小学时学到的

完成最佳答案:

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

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

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