JavaScript Program to Add Digits of a Number

In this article, you will learn how to add the digits of a number in JavaScript. Here is the list of JavaScript programs you will go through:

Add the digits of a number in JavaScript without user input

This program does not allow the 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 shows 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.

Add the digits of a given number in JavaScript

This program allows the user to enter the number, then find and print the sum of the 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 the Previous Program

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

Enter the Number:

Result =

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

JavaScript Online Test


« Previous Program Next Program »


Liked this article? Share it!





Like/follow us on social media for updates!




Like/follow us on social media for updates!