Ran into a very strange problem sometime back. I had to write a simple piece of code, subtract two number and return the result. Sounds simple doesn’t it, it was but not initially.

The problem was, if the last two digits were different, the program would return ‘0’. If say the last three digits were different, it would return ‘256’ or ‘512’ or something like that. In short I was not getting the correct result for subtraction.

var num1 = $.trim( $(‘#textbox1’).val() ); var num2 = $.trim( $(‘#textbox2’).val() ); $(‘#textbox3’).val( num1 - num2 );

I had other validations in place to make sure ‘num1’ is always greater then ‘num2’. Tried using parseInt, still the same result.

$(‘#textbox3’).val( parseInt( num1 - num2 ) );

Not sure what to do, I checked with my colleague Rahil (website). One look and he asked me, what’s the range for ‘int’? I never thought on those lines! A quick google search showed me that the max value for an ‘number’ in JavaScript is ‘9007199254740992’ and in my scenario both the numbers were 19 digits long. Did a google search to check if we have JavaScript long int. Turns out there is no JavaScript long int.

Fortunately for me only last 5-7 digits would be different between the two numbers.

The two numbers would be something like this :

**num1** : 1234567890123456789

**num2** : 1234567890123987654

Here is what I did, compare each character from num1 and num2 (string values). And wherever the characters are not equal, we extract the remaining characters starting from that character till the end. This will give us two new values and these values will be within the number range. Now we can do normal subtraction and get the correct result. Here is the function :

function subNums( startVal, endVal ){ var newStartVal = '', newEndVal = ''; for( var i = 0; i < endVal.length; i++ ){ if( startVal[i] != endVal[i] ){ newStartVal = startVal.substring(i,startVal.length); newEndVal = endVal.substring(i,endVal.length); return ( Math.abs( newEndVal - newStartVal ) ); } } }

Lucky for me I could get over this problem with a small function. That worked for me, I would love to know if anyone else came across something like this and how you handled it.

JavaScript Long int anyone :P.

Get complete code on github