Different result when using parseFloat [duplicate]

2

I just need to take two decimals of a number with the toFixed (2) method and for that I have to convert the numbers to parseFloat because otherwise the toFixed method fails me. The problem is that they give me wrong numbers and I do not know why.

var x=0;
var y=0;
var T=127.76;
var c=63.88;
var ci=110.64;

Without using parseFloat and toFixed;

var x1=x+ci;//110.64809081046089
var y1=y-c;//-63.882705014737745
var x2=x1+c;//174.53079582519862
var y2=y1+ci;//46.76538579572314

When using parseFloat and toFixed the result misses;

var x1=x+ci;//110.64809081046089
x1=parseFloat(x1);//110.64809081046089
x1=x1.toFixed(2);//110.65
var y1=y-c;//-63.882705014737745
y1=parseFloat(y1);//-63.882705014737745
y1=y1.toFixed(2);//-63.88

Here already calculates me wrong operations

var x2=x1+c;//110.6563.882705014737745 Y DEBERIA DAR 174.53079582519862
x2=parseFloat(x2);
x2=x2.toFixed(2);
var y2=y1+ci;//-63.88 Y DEBERIA DAR 46.76538579572314
y2=parseFloat(y2);
y2=y2.toFixed(2);

I do not understand why these results are wrong.

    
asked by Andrés 20.09.2018 в 12:37
source

2 answers

4

The problem you have is that you are messing between the floats and those that you consider to be string.

The solution would be to parslate all the variables at the beginning

var x=parseFloat(0);
var y=parseFloat(0);
var T=parseFloat(127.76);
var c=parseFloat(63.88);
var ci=parseFloat(110.64);

or do it to everyone during operations

var x2=x1+parseFloat(c);
x2=parseFloat(x2);
x2=x2.toFixed(2);
var y2=y1+parseFloat(ci);
y2=parseFloat(y2);
y2=y2.toFixed(2);
    
answered by 20.09.2018 в 12:52
3

What is happening to you is a fairly common error when operating with variables that contain numerical values. And it is necessary to be very clear about the type of content with which we are working. This is one of your erroneous results:

var x2=x1+c;//110.6563.882705014737745 Y DEBERIA DAR 174.53079582519862

What you expect is that the variable x2 will contain the sum of the variable x1 and the variable c . And here we have the problem. The variable c in your code is being treated as a string, so instead of adding its value to x1 it is concatenated, resulting in what you put:

110.6563.882705014737745

What I would do would be to force c to be also a number making it parseFloat() and the same with the other variables that operate in the formulas that are giving you wrong results.

    
answered by 20.09.2018 в 12:54