Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Sum Values

Tags:

javascript

I need to sum several values in javascript. I've tried by using following code

var a = 2;
var b = 5;
c = a+b;

But, instead of calculating the values of a and b, the output (c) only combine those two values. So the output given is :

c = 25

I believe you guys can help me easily about this. Thx before. Regard Andha.

like image 832
Andha Avatar asked Aug 13 '11 21:08

Andha


People also ask

Is there a sum () in JavaScript?

sum() function in D3. js is used to return the sum of the given array's elements. If the array is empty then it returns 0. Parameters: This function accepts a parameters Array which is an array of elements whose sum are to be calculated.

What does += mean in JavaScript?

The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator.


4 Answers

Make sure the values are numbers, otherwise they will concat instead of suming.

a = parseInt(a, 10); // a is now int 
like image 140
kjetilh Avatar answered Oct 15 '22 11:10

kjetilh


Your code is adding (concatenating) strings. Are you sure that the code you posted represents your problem? What you have written should work. Be sure in the real code you're not saying:

var a = '2'; // or something similar

Or if the values are parsed from somewhere, be sure to call parseInt(a, 10) on them before doing the addition, 10 being the radix.

Or as pointed out in the comments the Number function would probably suit your purposes.

like image 45
numbers1311407 Avatar answered Oct 15 '22 13:10

numbers1311407


The author has probably put "simplified" code so we can get an idea. Had same problem, while getting input values. JS interpreted it as string. Using "Number()" solved the problem:

var sum = Number(document.getElementById("b4_f2_"+i).value) + Number(document.getElementById("b4_f3_"+i).value) + Number(document.getElementById("b4_f4_"+i).value);
like image 20
dMole Avatar answered Oct 15 '22 12:10

dMole


This works fine:

var a = 2; 
var b = 5; 
var c = a + b; // c is now 7
like image 34
Jordão Avatar answered Oct 15 '22 13:10

Jordão