Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
38
rated 0 times [  45] [ 7]  / answers: 1 / hits: 22444  / 9 Years ago, mon, may 4, 2015, 12:00:00

I want to Split a number into its digit (for example 4563 to 4 , 5 , 6 , 3 ) then addiction this digits. (for example: 4+5+6+3=18)



I can write code for 3 digit or 2 digit and ... numbers seperately but I cant write a global code for each number.



so this is my code for 2 digit numbers:



var a = 23
var b = Math.floor(a/10); // 2
var c = a-b*10; // 3
var total = b+c; // 2+3
console.log(total); // 5


and this is my code for 3 digit numbers:



var a = 456
var b = Math.floor(a/100); // 4
var c = a-b*100; // 56
var d = Math.floor(c/10); // 5
var e = c-d*10; // 6
var total = b+d+e; // 4+5+6
console.log(total); // 15


but I cant write a code to work with each number.How can I write a global code for each number?


More From » javascript

 Answers
10



var num = 4563;
var sum = 0;
while(num > 0) {
sum += num % 10;
num = Math.floor(num / 10);
}
console.log(sum);




[#66762] Friday, May 1, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
claudiofredye

Total Points: 583
Total Questions: 101
Total Answers: 115

Location: Sao Tome and Principe
Member since Wed, Dec 29, 2021
2 Years ago
;