简体   繁体   中英

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:

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

Everything working fine, after every click number is changed in span: 1.01, 1.02. But after thrid click I see 3.0300000000000002. After fourth click I see again properly 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/

Since floating point math is inherently imprecise, try using toFixed() to round it to a suitable number of digits:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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