简体   繁体   English

jQuery,javascript - 如何添加十进制数?

[英]jQuery, javascript - How add decimal numbers?

I have created function after button click: 按钮点击后我创建了功能:

var cena_poczatkowa = parseFloat($("#cena_aktualna").text());
    var cena_dodana = cena_poczatkowa + 1.01;
    $("span#cena_aktualna").text(cena_dodana);

And span in html: 跨越html:

<span id="cena_aktualna">0.00</span>

Everything working fine, after every click number is changed in span: 1.01, 1.02. 在每个点击数字之后,一切正常工作在范围内改变:1.01,1.02。 But after thrid click I see 3.0300000000000002. 但是在thrid点击后我看到3.0300000000000002。 After fourth click I see again properly 4.04. 第四次点击后,我再次看到4.04。 Why after third click I see this strange number? 为什么在第三次点击后我看到这个奇怪的号码

Here is my working script so you can see this bug: http://jsfiddle.net/H3pfH/ 这是我的工作脚本,所以你可以看到这个bug: http//jsfiddle.net/H3pfH/

Since floating point math is inherently imprecise, try using toFixed() to round it to a suitable number of digits: 由于浮点数学本质上是不精确的,尝试使用toFixed()将其四舍五入到合适的位数:

var cena_dodana = (cena_poczatkowa + 1.01).toFixed(4);

http://jsfiddle.net/H3pfH/1/ http://jsfiddle.net/H3pfH/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM