4

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/

Lucas
  • 2,924
  • 8
  • 27
  • 32
  • 1
    Possible duplicate (http://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem). – maerics Aug 23 '11 at 12:55

1 Answers1

5

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/

Matt
  • 74,352
  • 26
  • 153
  • 180
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • 1
    +1 for using `toFixed()`, but I'd suggest fixing it when there is the need to display the result, and not when calculating the number data, like so: ` $("span#cena_aktualna").text(cena_dodana.toFixed(2));` – Cipi Aug 23 '11 at 13:03
  • Good point. It all depends on what said number is being used for elsewhere in the code. In this case, I would prefer to round it immediately since it corrects an error and makes the result *more* correct. If I were taking square roots or some other computation that I would expect to produce a long decimal value, I would round it at the end. – Blazemonger Aug 23 '11 at 13:06