我给它的价格是 19.90,它输出 19.98,原始计算是:
$('#price').text((Math.floor(price * 100) / 100) + ' Euro');
这是一个带有 Math.floor 部分的 JsFiddle,这是一个给出问题的部分:
我期待它再次给19.9!
我给它的价格是 19.90,它输出 19.98,原始计算是:
$('#price').text((Math.floor(price * 100) / 100) + ' Euro');
这是一个带有 Math.floor 部分的 JsFiddle,这是一个给出问题的部分:
我期待它再次给19.9!
在您的特定情况下,您可能应该切换Math.round()
以应对使用浮点运算时的不准确性。
$('#price').text((Math.round(price * 100) / 100) + ' Euro');
当您查看内部演示文稿时,您会看到如下内容:
19.90 * 100
> 1989.9999999999998
JavaScript 浮点数不能准确地表示您的数字,但使用接近您的实数的数字。当你现在使用Math.floor()
这个值时,你得到19.89
的是19.90
.
为了对这个主题有一个大致的了解,我建议您参考这个问题: