The problem is that you are concatenating strings, (returning from toFixed
) and not adding numbers:
var x = 0;
x = parseFloat((x + 0.4)).toFixed(1); // "0.4" <-saída verdadeira
x = parseFloat((x + 0.4)); // "0.40.4" que depois de parseFloat e toFixed vira "0.4" novamente
The first "sum" gives "0.40.4", and the parsefloat takes as far as it understands (the first "0.40").
One solution would be this:
var x = 0;
x = parseFloat((x + 0.4).toFixed(1) ); // 0.4
document.body.innerHTML += x + '<br>';
x = parseFloat((x + 0.4).toFixed(1) ); // 0.8
document.body.innerHTML += x + '<br>';
x = parseFloat((x + 0.4).toFixed(1) ); // 1.2
document.body.innerHTML += x + '<br>';
Notes:
-
The "tofixed" in this case could be applied in another order, for example at the time of displaying on the screen only. I just kept the code so you could compare with the original.
-
I changed the alert
to innerHTML
just to make it easier to read here on the page.
Put simply:
var x = 0;
x += 0.4 // 0.4
document.body.innerHTML += x.toFixed(1) + '<br>';
x += 0.4 // 0.8
document.body.innerHTML += x.toFixed(1) + '<br>';
x += 0.4 // 1.2
document.body.innerHTML += x.toFixed(1) + '<br>';
Here we simply parseFloat, since toFixed was used only when displaying on the screen, without disturbing the sums.