user3499381
user3499381

Reputation: 467

Trouble making a correct sum

I'm calculating standard deviation for a graph and although I'm getting the correct values for the square of each point on the graph, I'm having trouble getting the sum of the squared values. I should get 17.20 but am getting 14 instead. It only seems to be adding the first number and not the decimal places. Here is my code:

var1 = (var1 * var1).toFixed(2); //alert(var1); getting 2.56
var2 = (var2 * var2).toFixed(2); //alert(var2); getting 1.96
var3 = (var3 * var3).toFixed(2); //alert(var3); getting 5.76
var4 = (var4 * var4).toFixed(2); //alert(var4); getting 6.76
var5 = (var5 * var5).toFixed(2); //alert(var5); getting 0.16

var sum = (  parseInt(var1)+parseInt(var2)+parseInt(var3)+parseInt(var4)+parseInt(var5) ).toFixed(2);

alert(sum); // should get 17.20, but getting 14

Upvotes: 1

Views: 241

Answers (4)

Florian Neumann
Florian Neumann

Reputation: 5857

You shouldn't use parseInt since it converts your Float-values into Integers, which means each product is being flattened:

2 + 1 + 5 + 6 + 0 = 14

To achieve the right result you could also write:

var1 = Math.pow(var1, 2);
var2 = Math.pow(var2, 2);
var3 = Math.pow(var3, 2);
var4 = Math.pow(var4, 2);
var5 = Math.pow(var5, 2);

var sum = var1 + var2 + var3 + var4 + var5;

alert(sum.toFixed(2));

Or to write less lines:

var fixedSum = [var1, var2, var3, var4, var5].reduce(function(acc, curr){
  return acc + Math.pow(curr, 2)
}, 0).toFixed(2);

Upvotes: 1

Sean Cogan
Sean Cogan

Reputation: 2586

There's no reason for you to be using parseInt here unless you only want to sum the integer parts of the squares.

parseInt "parses a string and returns an integer." If you change the parseInt calls for each square to parseFloat, it will correctly parse the floating point values from your strings and sum them properly.

Upvotes: 1

Adam  M.
Adam M.

Reputation: 1193

This is because you are parsing each variable to an integer, cutting off the decimal places

Integers are whole numbers so your real operation is this:

var1 2.56->2  + var2:1.96->1 ...
parseInt(var1)+parseInt(var2)+parseInt(var3)+parseInt(var4)+parseInt(var5) ).toFixed(2);

you'll want to remove the ParseInt and just sum them together as such:

sum = (var1 + var2 + var3 + var4 +var5).toFixed(2);

I would also suggest you round (use toFixed) only once, as continually rounding decreases accuracy and in Javascript, it makes the numbers into strings which would cause unexpected results.

Upvotes: 0

Dion Zac
Dion Zac

Reputation: 69

You're getting the integer sum and not the decimals because you parseInt the strings. Just use parseFloat instead and it will work.

Upvotes: 0

Related Questions