提问人:MistaJase 提问时间:6/8/2023 最后编辑:MistaJase 更新时间:6/8/2023 访问量:26
Javascript 舍入问题 - 尝试使用不同的方法获得不同的结果
Javascript rounding issue - trying with different methods with different results
问:
我知道这个问题以前有人问过,我尝试了多种解决方案都没有成功,而且似乎比看起来更复杂......
我在应用折扣后处理产品价格,因此我将数字四舍五入到小数点后 2 位
所以以这个示例代码为例,希望每个数字都四舍五入,但有时它会四舍五入......
let numbers = []
numbers.push(1.782);
numbers.push(4.705);
numbers.push(4.715);
numbers.push(4.725);
numbers.push(4.735);
numbers.push(4.745);
numbers.push(4.755);
numbers.push(4.765);
numbers.push(4.775);
numbers.push(4.785);
numbers.push(4.795);
for (let i=0; i<numbers.length; i++){
console.log('TEST 1 - num#'+i+ ' ['+numbers[i]+'] toFixed = '+ (numbers[i]).toFixed(2) )
}
function roundToDecimal(num) {
return Math.round(num * 100) / 100
}
for (let i=0; i<numbers.length; i++){
console.log('TEST 2 - num#'+i+ ' ['+numbers[i]+'] roundToDecimal = '+ roundToDecimal(numbers[i]) )
}
返回:
TEST 1 - num#0 [1.782] toFixed = 1.78
TEST 1 - num#1 [4.705] toFixed = 4.71
TEST 1 - num#2 [4.715] toFixed = 4.71 // wrong
TEST 1 - num#3 [4.725] toFixed = 4.72 // wrong
TEST 1 - num#4 [4.735] toFixed = 4.74
TEST 1 - num#5 [4.745] toFixed = 4.75
TEST 1 - num#6 [4.755] toFixed = 4.75 // wrong
TEST 1 - num#7 [4.765] toFixed = 4.76 // wrong
TEST 1 - num#8 [4.775] toFixed = 4.78
TEST 1 - num#9 [4.785] toFixed = 4.79
TEST 1 - num#10 [4.795] toFixed = 4.79
TEST 2 num#0 [1.782] roundToDecimal = 1.78
TEST 2 num#1 [4.705] roundToDecimal = 4.71
TEST 2 num#2 [4.715] roundToDecimal = 4.72
TEST 2 num#3 [4.725] roundToDecimal = 4.72 // wrong
TEST 2 num#4 [4.735] roundToDecimal = 4.74
TEST 2 num#5 [4.745] roundToDecimal = 4.75
TEST 2 num#6 [4.755] roundToDecimal = 4.76
TEST 2 num#7 [4.765] roundToDecimal = 4.76 // wrong
TEST 2 num#8 [4.775] roundToDecimal = 4.78
TEST 2 num#9 [4.785] roundToDecimal = 4.79
TEST 2 num#10 [4.795] roundToDecimal = 4.8
我知道浮点符号问题......但这太不一致了,我不确定如何进行!
有没有人有可行的解决方案?
答: 暂无答案
评论
Number
numbers
Numbers
Number