This question already has answers here:
Is floating point math broken?
                                
                                    (31个答案)
                                
                        
                                4个月前关闭。
            
                    
我正在尝试打印11到30的整数乘以0.015

for ( let i = 11; i <= 30; i++ ) {
    console.log( `${i} * 0.015 = ${i * 0.015}` );
}


我希望输出看起来像这样:

11 * 0.015 = 0.165
12 * 0.015 = 0.18
13 * 0.015 = 0.195
14 * 0.015 = 0.21
15 * 0.015 = 0.225
16 * 0.015 = 0.24
17 * 0.015 = 0.255
18 * 0.015 = 0.27
19 * 0.015 = 0.285
20 * 0.015 = 0.3
21 * 0.015 = 0.315
22 * 0.015 = 0.33
23 * 0.015 = 0.345
24 * 0.015 = 0.36
25 * 0.015 = 0.375
26 * 0.015 = 0.39
27 * 0.015 = 0.405
28 * 0.015 = 0.42
29 * 0.015 = 0.435
30 * 0.015 = 0.45


相反,我得到这个:

11 * 0.015 = 0.16499999999999998
12 * 0.015 = 0.18
13 * 0.015 = 0.195
14 * 0.015 = 0.21
15 * 0.015 = 0.22499999999999998
16 * 0.015 = 0.24
17 * 0.015 = 0.255
18 * 0.015 = 0.27
19 * 0.015 = 0.285
20 * 0.015 = 0.3
21 * 0.015 = 0.315
22 * 0.015 = 0.32999999999999996
23 * 0.015 = 0.345
24 * 0.015 = 0.36
25 * 0.015 = 0.375
26 * 0.015 = 0.39
27 * 0.015 = 0.40499999999999997
28 * 0.015 = 0.42
29 * 0.015 = 0.435
30 * 0.015 = 0.44999999999999996


我环顾了StackOverflow,看来JavaScript的浮点精度存在问题。因此,我尝试了一种将数字四舍五入到任意步骤的方法:

function round( number, step ) {
    const inverseStep = 1 / step;
    return Math.round( number * inverseStep ) / inverseStep;
}

for ( let i = 11; i <= 30; i++ ) {
    const rounded = round( i * 0.015, 0.015 );
    console.log( `${i} * 0.015 = ${rounded}` );
}


而且,我仍然可以使用奇怪的无理小数位数获得相同的结果。

最佳答案

浮点精度足以完成任务,您只需要四舍五入即可。您可以使用

.toFixed(2)


将结果四舍五入到小数点后两位。

请注意,这会将您的结果转换为字符串(这对您正在做的事情很好),因此,如果您转换回浮点,则将返回不准确性。如果您真的担心确切的值,则应使用Decimal.js之类的东西,它将数字作为字符串而不是浮点数处理。尤其是如果您正在做算钱之类的事情时。

关于javascript - 如何将11到30之间的整数乘以0.015? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57684335/

10-09 17:36