Sum of values in variable does not occur, tofixed

2

It was for him to add up .. but it did not happen, I added parsefloat because I was giving error that it was not a function ..

var x = 0;
x = parseFloat((x + 0.4)).toFixed(1); // 0.4
x = parseFloat((x + 0.4)).toFixed(1); // 0.8
alert(x); // 0.8
x = parseFloat((x + 0.4)).toFixed(1); // 1.2
alert(x); // 1.2

It should be like in the comments but .. what's the problem? Is ToFixed doing something wrong? It always returns 0.4

link

    
asked by anonymous 10.04.2015 / 00:18

2 answers

4

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.

    
10.04.2015 / 00:52
1

The problem is that these numbers are in string format and not number .

What these methods return:

Accepts a string and converts to number without rounding. The similar method that rounds integers is parseInt(string, base); . Returns in number format.

Accepts a number with decimals (fractional part). Returns a string .

Suggestion:

I suggest creating a function that does this, and can handle different cases:

function soma(a, b, casasDecimais) {
    if (typeof a == 'string') a = parseFloat(a);
    if (typeof b == 'string') b = parseFloat(b);
    var soma = a + b;
    return soma.toFixed(casasDecimais);
}

jsFiddle: link

    
10.04.2015 / 07:23