当尝试将 3 位小数的数字舍入为 2 位小数的数字时,toFixed()
无法正确舍入最新数字。但是,当我对 4 位小数的数字做同样的事情时,它确实有效......我无法理解这是怎么回事。
我见过一些解决方案,例如 Math.round(value * 100)/100
,但它总是向下舍入到小数点后两位,而我想要一个通用函数进行舍入,您可以在其中输入要舍入的小数位数。
目前的功能是这样的:
Number.prototype.round = function (precision: number = 2) {
return Number(this.toFixed(precision));
}
关于如何解决这个问题有什么想法吗?
const value = 51.425;
console.log('To fixed with 3 decimals: ', value.toFixed(2));
const value2 = 51.4251;
console.log('To fixed with 4 decimals: ', value2.toFixed(2));
最佳答案
JavaScript 中的 float 是 broken正如 @Jaromanda 和 @dan_pran 提到的。
但是 Math.round()
解决方案仍然适用于您的用例 - 只是多了一些代码:
Number.prototype.round = function (precision = 2) {
return Math.round(this * 10 ** precision) / 10 ** precision;
}
const value = 51.425;
console.log('Rounded with 3 decimals: ', value.round(2));
const value2 = 51.4251;
console.log('Rounded with 4 decimals: ', value2.round(2));
const value3 = 51.4215;
console.log('Rounded with 4 decimals: ', value3.round(3));
关于当数字有 3 位小数并固定为 2 位小数时,Javascript number.toFixed() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76571698/