你能四舍五入一个数字在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

其他回答

如果你的源代码是typescript,你可以使用这样的函数:

public static ToFixedRounded(decimalNumber: number, fractionDigits: number): number {
    var rounded = Math.pow(10, fractionDigits);
    return (Math.round(decimalNumber * rounded) / rounded).toFixed(fractionDigits) as unknown as number;
}
var num = 34.7654;

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

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

使用toprecprecision方法:

var a = 1.2345
a.toPrecision(2)

// result "1.2"
Math.round( mul/count * 10 ) / 10

Math.round(Math.sqrt(sqD/y) * 10 ) / 10

谢谢

var number = 123.456;

console.log(number.toFixed(1)); // should round to 123.5