Sum all the digits of a number Javascript
Asked Answered
D

8

26

I am newbie.

I want to make small app which will calculate the sum of all the digits of a number.

For example, if I have the number 2568, the app will calculate 2+5+6+8 which is equal with 21. Finally, it will calculate the sum of 21's digits and the final result will be 3 .

Please help me

Duelist answered 12/7, 2016 at 16:40 Comment(4)
If you treat the number as a string ('2568'), then split the string on every character (str.split('')), you will have every digit listed out separately in an array. Each digit is still a string, but you can then cast each to a number and add them up. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Ferren
How could I tell the script to take the number from a specific input instead of a given number?Duelist
jsfiddle.net/18hc4hgd my work so farDuelist
Possible duplicate of sum of the digits of a number javascriptDues
G
55

Basically you have two methods to get the sum of all parts of an integer number.

  • With numerical operations

    Take the number and build the remainder of ten and add that. Then take the integer part of the division of the number by 10. Proceed.

var value = 2568,
    sum = 0;

while (value) {
    sum += value % 10;
    value = Math.floor(value / 10);
}

console.log(sum);
  • Use string operations

    Convert the number to string, split the string and get an array with all digits and perform a reduce for every part and return the sum.

var value = 2568,
    sum = value
        .toString()
        .split('')
        .map(Number)
        .reduce(function (a, b) {
            return a + b;
        }, 0);

console.log(sum);

For returning the value, you need to addres the value property.

rezultat.value = sum;
//      ^^^^^^

function sumDigits() {
    var value = document.getElementById("thenumber").value,
        sum = 0;

  while (value) {
      sum += value % 10;
      value = Math.floor(value / 10);
  }
  
  var rezultat = document.getElementById("result");
  rezultat.value = sum;
}
<input type="text" placeholder="number" id="thenumber"/><br/><br/>
<button onclick="sumDigits()">Calculate</button><br/><br/>
<input type="text" readonly="true" placeholder="the result" id="result"/>
Gesellschaft answered 12/7, 2016 at 18:21 Comment(7)
Thank you very muchDuelist
@Nina, why modulo 10 exactly? Would you mind expanding on that?Willing
@Daniel, the remainder operator is for getting the digit for adding to sum.Gesellschaft
for the second solution "Use string operations" If I use the number 0123 instead of 2568 answer is wrong.Methionine
@ChetanNada, numbers with leading zero are interpreted as octal values. please have a look here.Gesellschaft
@NinaScholz So what is the solution for this? if any number leads with zero then the answer is unexpected!Methionine
don't use constant values with leading zero.Gesellschaft
M
40

How about this simple approach using modulo 9 arithmetic?

function sumDigits(n) {
  return (n - 1) % 9 + 1;
}
Midland answered 25/11, 2017 at 13:7 Comment(16)
Excellent example, though I personally do not fully get the idea how this works ... I mean, suppose n = 12, then 12-1 = 11, 11 % 9 = 1 and 1 + 1 = 2, yet it should be 3 ...Sidky
Actually 11 % 9 = 2, not 1, so 1 + 2 = 3Midland
note: it finds the sum of digits recursively (it is not clear from the title of the question and the accepted answer)Hoopes
@Sidky ignore the -1 and +1, then it is just n%9. Since a number n=10^k*a_k + 10^(k-1)*a_(k-1)...10^0*a_0. Modulo 9 removes all all 10^i, since 10^i mod 9 = 1. Then the sum is created modulo 9 as well. When you imagine -1 shifts the whole number line by one to the left, you get also the nines correctly. After that you simply add 1 again.Gauntlett
This is elegant! I had to read about modulo 9 arithmetic to understand it.Cotinga
@FedericoAntonucci However, the function seems to fail if n % 9 = 1Cotinga
@R3l1c not really, on which value for n you consider the function fails? For example taking 10: 10 % 9 = 1 -> (10 - 1) % 9 + 1 -> 9 % 9 + 1 -> 0 + 1 -> 1Midland
@FedericoAntonucci Apparently it fails for all numbers greater than 10 which have remainder 1 on division with 9. For eg. 19, 28, 37, 46, ... and so on. The function should return 10 for these cases but instead returns 1.Cotinga
@R3l1c the function should return rhe sum recursively, that's exactly what the question asks, read it again please. This solution works perfect for this questionMidland
This should be the answer. This is much faster and much more elegantMayfair
Usage of that function was a waste of time for me, because I didn`t need the recursive version of the sum. I needed a function that just give immediate (intermediate) sum of digits. And this function fails for that case as noted by @Raknos13.Osteogenesis
Unfortunatelly it doesn't work all the time.Saffian
For example sumDigits(19) returns 1 instead of 2Saffian
1 is the right answer. 1 + 9 = 10 -> 1 + 0 = 1Midland
This returns 2 for 29 , (29-1)%9+1 = 28%9+1 = 1+ 1 =2 , but the expected result is 2+9 = 11Altricial
@Altricial the question was how to add recursively until getting only 1 digit, not to sum all digits. So 11 -> 1+1 = 2 Read the question again.Midland
O
5

With mathy formula:

function sumDigits(n) { 
    return (--n % 9) + 1;
}

Without mathy formula:

function sumDigits(n) {
    if (typeof n !== 'string') {
        n = n.toString();
    }    
    if (n.length < 2) {
        return parseInt(n);
    }
​
    return sumDigits(
        n.split('')
         .reduce((acc, num) => acc += parseInt(num), 0)
    );
}
Owens answered 26/4, 2021 at 15:42 Comment(0)
T
3

let's try recursivity

function sumDigits(n) {
  if (n < 10) return n
  return sumDigits(n % 10 + sumDigits(Math.floor(n / 10)))
}

sumDigits(2) // 2
sumDigits(2568) // 3
Transmitter answered 12/6, 2020 at 20:12 Comment(0)
O
2

The sum of digits can be calculated using that function (based on other answers):

function sumDigits(n) {
    let sum = 0;
    while (n) {
        digit = n % 10;
        sum += digit;
        n = (n - digit) / 10;
    }
    return sum;
}

If you really need to sum the digits recursively there is recursive version of the function:

function sumDigitsRecursively(n) {
    let sum = sumDigits(n);
    if (sum < 10)
        return sum;
    else
        return sumDigitsRecursively(sum);
}

The sumDigitsRecursively(2568) expression will be equal to 3. Because 2+5+6+8 = 21 and 2+1 = 3.

Note that recursive solution by @FedericoAntonucci should be more efficient, but it does not give you intermediate sum of digits if you need it.

Osteogenesis answered 30/5, 2020 at 10:32 Comment(5)
The question is about recursive sum of digitsMidland
@FedericoAntonucci but you didn't name your function as sumDigitsRecursively and it did confised me, because I was looking for the method to just sumDigits. My answer contains solution that gives the same results as yours. Why did you voted my answer down?Osteogenesis
cause recursive solution is no better than every other answer, and it's the less elegant solutionMidland
I got here when I was looking for just the sum of digits of the number, and the accepted answer do not contain a function that just receives the number and returns the sum. So I made it. Accepted solution makes a call to Math.float, but there is no need to do so. So for my task this is a better solution. Also the recursive version is only a bit less efficient than yours (and I wrote about it in the answer), but it is easy to understand. On the other hand you didn't explain how your solution work, and didn`t name it correctly so it caused the confusion for me and for @Raknos13.Osteogenesis
I was just answering the question, it didn't ask for what you are saying, you should read the whole question, not just the titleMidland
I
2

You could do it this way.

function sums(input) {
    let numArr = input.toString().split('');
    let sum = numArr.reduce((a, b) => Number(a) + Number(b));
    return sum < 10 ? sum : sums(sum);
}
Illhumored answered 26/8, 2021 at 4:35 Comment(1)
It is a good solution for huge numbers of strings. Thanks.Valaria
R
0

Expanding upon @fethe 's answer, this sumOfDigit function is able to handle large number or BigInt

function sumOfDigits(n) { 
  return (Number.isSafeInteger(n)) ? (--n % 9) + 1 : Number((--n % 9n) + 1n);
}

console.log(sumOfDigits(101)); // 2
console.log(sumOfDigits(84932)); // 8
console.log(sumOfDigits(900000000000000000000000009n)); // 9
Resting answered 30/7, 2021 at 4:43 Comment(0)
G
0

you can use this function and pass your number to it:

const solution = (n) => {
    const arr = `${n}`
    let sum = 0;
    for (let index = 0; index < arr.length; index++) {
        sum += parseInt(arr[index])
    }
    return sum;
}
Georgiannegeorgic answered 30/1, 2023 at 17:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.