Javascript Math.floor生成的数字低于预期

时间:2014-01-22 10:35:55

标签: javascript math floor

我给它的价格为19.90,输出为19.98,最初的计算是:

 $('#price').text((Math.floor(price * 100) / 100) + ' Euro');

这是一个只有Math.floor部分的JsFiddle,它是一个给出问题的部分:

http://jsfiddle.net/dLNnp/

我期待它再次给予19.9!

1 个答案:

答案 0 :(得分:0)

在您的特定情况下,您应该切换到Math.round()以应对使用浮点运算时的不准确性。

$('#price').text((Math.round(price * 100) / 100) + ' Euro');

当您查看内部演示文稿时,您会看到如下内容:

19.90 * 100
> 1989.9999999999998

JavaScript浮点数不能完全代表您的数字,而是使用接近实数的内容。现在,对此值使用Math.floor()时,您会获得19.89而不是19.90

为了全面了解这个主题,我建议你这个问题: