Skip to content
Sign upLog in
← Back to Community

How do I add multiple numbers in js?

Profile icon
vbsoffice

I am making a program which you add a ton of numbers to calculate the sum. So far, I got all the numbers in a variable like this:

var numbers = 123456;

How do I add all these up?

P.S: I can use a jquery solution as well!

Answered by RYANTADIPARTHI [earned 5 cycles]
View Answer
Voters
Profile icon
SummerGOLDSMITH
Profile icon
vbsoffice
Comments
hotnewtop
Profile icon
RYANTADIPARTHI

Use this:

var value = 2568, sum = 0; while (value) { sum += value % 10; value = Math.floor(value / 10); } console.log(sum);
Profile icon
vbsoffice

@RYANTADIPARTHI
Thank You! Works like a charm!

Profile icon
RYANTADIPARTHI

@vbsoffice
np. :)

Profile icon
Coder100

Well, I can only think of using an array:

let input = "1,2,3"; // input from html maybe let arr = input.split(","); let sum = arr.reduce((p, c) => p+c, 0); alert(sum);

does that help?

Profile icon
[deleted]
var firstNum = 123; var secondNum = 137; console.log(firstNum + secondNum);```
Profile icon
DynamicSquid

You add a bunch of numbers? So are the numbers stored in different variables? Why would you store them in a single variable???

Profile icon
OlauPla

@DynamicSquid
Yeah, at least an array

Profile icon
vbsoffice

@DynamicSquid
Because I use jquery to select all the classes and get the text of them, and it stores in a single string. Then, I use parseInt!

Profile icon
realTronsi

@vbsoffice
what, this makes no sense what you're doing. Anyways you can do

string.split("").reduce((a,b)=>a+b))

that should work, the string.split will split the numbers into 1, 2, 3, etc. and the reduce will add them together.

What I don't understand is why you don't store them in an array, storing them all in a string is such a bad idea.

    1. you can't determine multi-digit numbers
    1. have to split into array each time you use it
    1. probably more work
Profile icon
DynamicSquid

@vbsoffice
Why would you possibly want to store multiple numbers in one string? Just use an array?