Skip to content
Advertisement

How to add two big numbers in javascript?

I have two text boxes. Each will take input up to thousand digits.

Now i want to add these two numbers. My question is what data type should i use to store the result?

I have tried this:

<script>
   var x = 'Thousand digit of number'
    var y = 'Thousand digit of number'
    var z = x + y
</script>

but i am getting result in exponential form. How to store the result and display it?

Advertisement

Answer

Input the numbers as string and add each characters each other as array something like this:

 function add() {
        document.getElementById("demo").innerHTML = "";
        var x = document.getElementById("txt1").value;
        var y = document.getElementById("txt2").value;
        var len;
        var lenx = x.length;
        var leny = y.length;
        var x1,y1,rem,div=0;
        if(lenx>leny) len = lenx; else len = leny;

        for(var i=0;i<len;i++){
            if(i>=lenx) x1  = 0;
            else x1 = parseInt(x[lenx-i-1]);
            if(i>=leny) y1 = 0;
            else y1 = parseInt(y[leny-i-1]);
            rem = (x1+y1+div)%10;
            div = Math.floor((x1 + y1+div)/10);
            document.getElementById("demo").innerHTML = rem + document.getElementById("demo").innerHTML;
        }
       if(div>0){
            document.getElementById("demo").innerHTML = div + document.getElementById("demo").innerHTML;
       }
    }

Here the code: https://jsfiddle.net/mtsL1k2x/5/

Note: this is only for natural numbers. You can modify depending on your inputs

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement