How to split JavaScript Number into individual digits?

JavascriptWeb DevelopmentFront End Technology

To spilt a number into digits and print their sum, try to run the following code −

Example

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <script>
         var a = 28573;
         var sum = 0;
         while(a > 0) {
            sum += a % 10;
            a = Math.floor(a / 10);
         }
         document.write("Sum of digits = "+sum);
      </script>
   </body>
</html>

Output

Sum of digits = 25
raja
Published on 03-Feb-2018 13:29:18
Advertisements