JavaScript Program to Add Digits of a Number

In this article, you will learn and get code to add digits of a number in JavaScript. Here are the list of JavaScript programs, you will go through:

Add Digits of a Number in JavaScript

This program does not allows user to enter the data. That is, this program only adds all the digits of a number say 1234 and prints its addition result on output.

This is just a simple JavaScript code that reminds you, how the addition of all digits of a number gets performed

<!doctype html>
<html>
<body>
<script>
  var num=1234, rem, sum=0;
  while(num)
  {
    rem = num%10;
    sum = sum+rem;
    num = Math.floor(num/10);
  }
  document.write(sum);
</script>
</body>
</html>

Save this code in a file with .html extension and open it in a web browser. Here is the output:

javascript add digits of number

Note - The Math.floor() method rounds the number to its nearest integer. That is, Math.floor(12/10) gives you 1, instead of 1.2

The following code:

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

works in a way that:

The document.write() method writes the value of sum into an HTML output.

Get Input from User

This program allows user to enter the number, then find and prints the sum of digits of that entered (given) number as shown here:

<!doctype html>
<html>
<head>
<script>
function addDigitsOfNumber()
{
  var num, rem, sum=0;
  num = parseInt(document.getElementById("num").value);
  while(num)
  {
    rem = num%10;
    sum = sum+rem;
    num = Math.floor(num/10);
  }
  document.getElementById("result").value = sum;
}
</script>
</head>
<body>

<p>Enter the Number: <input id="num"></p>
<button onclick="addDigitsOfNumber()">Add Digits Of Number</button>
<p>Result = <input id="result"></p>

</body>
</html>

Here is its sample output with user input, 1234:

add digits of number javascript

Live Output of Previous Program

Here is the live output of above JavaScript program on addition of digits of given number by user:

Enter the Number:

Result =

After clicking on the button named Add Digits of Number, a function addDigitsOfNumber() gets called. Therefore, all the statements inside this function gets executed, and the value of input whose id is result gets changed with the value of sum.

JavaScript Online Test


« Previous Program Next Program »