Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of a string of one-digit numbers in javascript?

Tags:

javascript

I'm trying to write a script that adds the left side of a string and validates it against the right side.

For example:

var left = "12345"
var right = "34567"

I need to do some sort of sum function that adds 1+2+3+4+5 and checks if it equals 3+4+5+6+7.

I just don't have a clue how to do it.

I think I need to use a for loop to iterate through the numbers such as for (var i = 0, length = left.length; i < length; i++)

But I'm not sure how to add each number from there.

EDIT the var is actually being pulled in from a field. so var left = document.blah.blah

like image 867
SorryEh Avatar asked Apr 07 '12 06:04

SorryEh


People also ask

How do I sum a string of numbers in JavaScript?

Use the addition (+) operator, e.g. Number('1') + Number('2') . The addition operator will return the sum of the numbers.

How do you sum variables in JavaScript?

Add numbers in JavaScript by placing a plus sign between them. You can also use the following syntax to perform addition: var x+=y; The "+=" operator tells JavaScript to add the variable on the right side of the operator to the variable on the left.


3 Answers

DEMO

var left = "12345"
var right = "12345"

function add(string) {
    string = string.split('');                 //split into individual characters
    var sum = 0;                               //have a storage ready
    for (var i = 0; i < string.length; i++) {  //iterate through
        sum += parseInt(string[i],10);         //convert from string to int
    }
    return sum;                                //return when done
}

alert(add(left) === add(right));​
like image 133
Joseph Avatar answered Oct 05 '22 22:10

Joseph


  1. Find the length of the string
  2. then in a temp Variable store the value pow(10,length-1)
  3. if you apply module function (left%temp) you will ge the Last significant digit
  4. you can use this digit to add
  5. repeat the process till the length of the string left is 0 6 Repeat all the steps above for the right as well and then compare the values

Note: convert the string to int using parseInt function

like image 22
Pete Avatar answered Oct 05 '22 23:10

Pete


var sum = function(a,b){return a+b}

function stringSum(s) {
    var int = function(x){return parseInt(x,10)}
    return s.split('').map(int).reduce(sum);
}

stringSum(a) == stringSum(b)
like image 45
ninjagecko Avatar answered Oct 06 '22 00:10

ninjagecko