JQuery, javascript - How to add decimal numbers?

I created a function after clicking a button:

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 works fine, after each change in the click number in the range: 1.01, 1.02. But after the first click, I see 3.0300000000000002. After the fourth click, I see 4.04 correctly. Why after the third click do I see this strange number?

Here is my working script so you can see this error: http://jsfiddle.net/H3pfH/

+4
source share
1 answer

Since floating point math is essentially inaccurate, try using toFixed () to round it to the appropriate number of digits:

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

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

+5
source

All Articles