The problem is that you are concatenating strings, (return from toFixed
) and not adding up 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 when showing on screen only. I only kept it in the code so you could compare it to the original.
I switched the alert
for innerHTML
just to make it easier to read here on the page.
Making it even simpler:
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 take the parseFloat, because the toFixed was used only when displaying on screen, without disturbing the sums.
what function parsefloat in all this then, just turn string?
– Vinícius Lara
no, the parsefloat is just the reverse. the problem was the . tofixed off the ( ). ParseFloat, the way I did, makes toFixed again a number. The way you did, he turned number, but then the. toFixed made turning string again; i.e., parsefloat has to be applied after tofixed to be able to sum, and not before.
– Bacco
@user3163662 complemented the answer with one more example, see if help.
– Bacco