Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  36] [ 5]  / answers: 1 / hits: 19685  / 7 Years ago, tue, january 31, 2017, 12:00:00

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?


More From » javascript

 Answers
6

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


[#59136] Sunday, January 29, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marques

Total Points: 366
Total Questions: 108
Total Answers: 111

Location: Burundi
Member since Wed, Nov 25, 2020
4 Years ago
;