473,785 Members | 2,841 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to compare two 20 digit numbers in javascript

hi frnds,
Im having two 20digit numbers, But while comparing those it
is giiving wrong ouput in javascript.

for example here is my code,
my secanrio is ,

~ If first 20 digit number is greater number than second 20 digit
number ,then it should return.

* And another important thing is, the two 20digit number will be same
but last one digit only change

Code:

<HTML>
<script language='javas cript'>
function numberCheck()
{
var val1=document.g etElementById(' txt1').value;
var val2=document.g etElementById(' txt2').value;
if(parseInt(val 1) parseInt(val2))
alert("Greater" )
else
alert("Correct" );

}
</script>
<body>
<input type=text id="txt1" value="18446744 073709551617" size=25>
<input type=text id="txt2" value="18446744 073709551616" size=25>
<input type=button onclick="number Check();" value="check">

</body>
</html>

So here txt1 value is greater than txt2 value, but it returning Correct
alert.
Please tel me reason why its returning like this,
Is there any restriction for comparing more than 20 digits

Jul 28 '06 #1
11 17816
ba************* ****@gmail.com said the following on 7/28/2006 1:44 AM:
hi frnds,
Im having two 20digit numbers, But while comparing those it
is giiving wrong ouput in javascript.

for example here is my code,
my secanrio is ,

~ If first 20 digit number is greater number than second 20 digit
number ,then it should return.

* And another important thing is, the two 20digit number will be same
but last one digit only change
If the only thing that can change is the last digit then simply compare
the last character and it doesn't matter how long the "number" is if it
is stored in a string.
<HTML>
<script language='javas cript'>
function numberCheck()
{
var val1=document.g etElementById(' txt1').value;
var lastChar1 = val1.charAt(val 1.length-1);
var val2=document.g etElementById(' txt2').value;
var lastChar2 = val2.charAt(val 2.length-1);
Now, simply compare the last 2 characters.
if(parseInt(val 1) parseInt(val2))
Don't use parseInt without the second parameter or you may eventually
get unexpected results.

if (+lastChar1>+la stChar2)

<snip>
>
So here txt1 value is greater than txt2 value, but it returning Correct
alert.
Please tel me reason why its returning like this,
The incorrectness introduced by floating point math.
Is there any restriction for comparing more than 20 digits
Probably.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jul 28 '06 #2
ba************* ****@gmail.com wrote:
[...]
So here txt1 value is greater than txt2 value, but it returning Correct
alert.
Please tel me reason why its returning like this,
Is there any restriction for comparing more than 20 digits
Yes, absolutely.

If only the last digit needs to be compared, then Randy has answered
your question. However, if you want to compare large numbers as
numbers, read the following thread:

<URL:
http://groups.google.com/group/comp....73213f5f2e91c5
>
>From that thread:
"The representable range is +/-1.7976931348623 157×10^308 (with
numbers as small as +/-5×10^-324). The range of precise integer
values is +/-900719925474099 2 (+/-2^53)."

Note that there are many integers in the representable range that can't
be represented exactly, starting with integers of 16 digits. That is
well short of your requirement for 20 digits.
--
Rob

Jul 28 '06 #3
Hi Randy,

For a example only ,i told u the last character, It can be any digit in
the whole number, So i want to compare the whole 20 digit number with
other 20 digit number.

I want know ,why is it not comparing correctly. Is there anyother way
to compare

Jul 28 '06 #4
Hi Randy,

For a example only ,i told u the last character, It can be any digit in
the whole number, So i want to compare the whole 20 digit number with
other 20 digit number.

I want know ,why is it not comparing correctly. Is there anyother way
to compare

Jul 28 '06 #5
HI Rob,

Thanks for your information.

Then there no way to compare this. My senario is like that,
what can i do to solve this problem.
Can u give me a suggestion.

Jul 28 '06 #6
ba************* ****@gmail.com said the following on 7/28/2006 2:51 AM:
Hi Randy,

For a example only ,i told u the last character, It can be any digit in
the whole number, So i want to compare the whole 20 digit number with
other 20 digit number.
The value of a text input is a string. Do a string comparison and you
don't run into the 16 digit limit.
I want know ,why is it not comparing correctly. Is there anyother way
to compare
Compare them as strings.

if (string1 == string2)
--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jul 28 '06 #7

ba************* ****@gmail.com wrote:
HI Rob,

Thanks for your information.

Then there no way to compare this. My senario is like that,
what can i do to solve this problem.
Can u give me a suggestion.
An algorithm is:

- get the values as strings (input elements will return strings)
- check they are both integers
- remove leading zeros
- the longest one is bigger
- if they are the same length, check digit by digit
- if the numbers are really big, chec, blocks of say
10 digits at a time.

e.g. the following example returns true only if a and b are integers
and a is bigger than b. If a or b aren't integers, 'undefined' is
returned. Otherwise, if b is bigger or equal to a, false is returned.

function isBigger(a, b)
{
// Make sure they are integers
var re = new RegExp('\\D','g ');
if (re.test(a) || re.test(b)){
return undefined;
}

// Trim leading zeros
a = a.replace(/^0+/g,'');
b = b.replace(/^0+/g,'');

// Check lengths
if (a.length != b.length){
return (a.length b.length);
}

// Compare digits
var a = a.split('');
var b = b.split('');
for (var i=0, j=a.length; i<j; i++){
if (+a[i] b[i]) return true;
}
return false;
}

Jul 28 '06 #8
RobG said the following on 7/28/2006 5:07 AM:
ba************* ****@gmail.com wrote:
>HI Rob,

Thanks for your information.

Then there no way to compare this. My senario is like that,
what can i do to solve this problem.
Can u give me a suggestion.

An algorithm is:

- get the values as strings (input elements will return strings)
- check they are both integers
- remove leading zeros
If they are defined in the HTML then you can be pretty assured whether
they are numbers or not, but even then, comparing them as strings is
simpler and easier. After removing the leading zeros, if they are equal
as strings they must be equal as numbers. If they aren't equal as
strings then they aren't equal as numbers.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jul 28 '06 #9

RobG wrote:
ba************* ****@gmail.com wrote:
HI Rob,

Thanks for your information.

Then there no way to compare this. My senario is like that,
what can i do to solve this problem.
Can u give me a suggestion.

An algorithm is:

- get the values as strings (input elements will return strings)
- check they are both integers
- remove leading zeros
- the longest one is bigger
- if they are the same length, check digit by digit
- if the numbers are really big, chec, blocks of say
10 digits at a time.

e.g. the following example returns true only if a and b are integers
and a is bigger than b. If a or b aren't integers, 'undefined' is
returned. Otherwise, if b is bigger or equal to a, false is returned.

function isBigger(a, b)
{
// Make sure they are integers
var re = new RegExp('\\D','g ');
if (re.test(a) || re.test(b)){
return undefined;
}

// Trim leading zeros
a = a.replace(/^0+/g,'');
b = b.replace(/^0+/g,'');

// Check lengths
if (a.length != b.length){
return (a.length b.length);
}

// Compare digits
var a = a.split('');
var b = b.split('');
for (var i=0, j=a.length; i<j; i++){
if (+a[i] b[i]) return true;
}
return false;
}
Rob, I think you've got a great solution for the problem.
But, I'm going to offer up something a little more general purpose.
Inspired by Java's BigDecimal object. I'm going to propose a BigInteger
for java that will allow for comparison of really large numbers.
/*
* Representation of a big integer.
* the compare method returns a value greater than zero if the
comparing
* object is greater, a negative number if the object compared is
greater,
* or zero if the objects are equal.
*/
function BigInteger(strV al) {
this.parts = new Array();
for(var i=0; i<strVal.length ; i++){
this.parts[i] = +strVal.charAt( i);
}
this.compare = function(num){
var thisLength = this.parts.leng th;
var numLength = num.parts.lengt h;
var greater = 0;
if(thisLength == numLength && thisLength>0){
var cnt = thisLength-1;
while( greater==0 && cnt >= 0 ){
greater = this.parts[cnt] - num.parts[cnt];
cnt--;
}
} else {
greater = (thisLength numLength)?(1): (-1);
}
return greater;
}
}
Granted, creating an array of numbers is probably overkill for simple
comparison it does simplify extending to allow mathematical operations
pretty easily.

The original number check function could be modified to use this like:
function numberCheck()
{
var val1=document.g etElementById(' txt1').value;
var val2=document.g etElementById(' txt2').value;
var val1Bigint = new BigInteger(val1 );
var val2Bigint = new BigInteger(val2 );

var comp = val1Bigint.comp are(val2Bigint) ;
if(comp==0) {
alert("Equal");
} else if(comp>0){
alert("Greater" )
} else {
alert("Less");
}
}

Jul 28 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
32656
by: Rune Strand | last post by:
Hi, If I have a lot of integers and want do something with each digit as integer, what is the fastest way to get there? Eg. Make 12345 into an iterable object, like or "12345" (Btw: What is the English term for this process; itemize? tokenize? digitize? sequence?) Some examples:
4
5391
by: Richard Hollenbeck | last post by:
I'm trying to write some code that will convert any of the most popular standard date formats twice in to something like "dd Mmm yyyy" (i.e. 08 Jan 1908) and compare the first with the second and calculate days, months, and years. This is not for a college course. It's for my own personal genealogy website. I'm stumped about the code. I'm working on it but not making much progress. Is there any free code available anywhere? I know it...
11
2987
by: Nobody | last post by:
Heres the deal... I have an application where I have a list (as in a Windows list control, but thats not important) displayed to the user. I sort this list based on the list controls sort function (again, its not important that its Windows) which ends up calling a compare function in my code: int CompareFunc(char* str1, char* str2) { } this function returns -1, 0 or 1 which gets passed on to the internal quick
3
1667
by: Dan Gidman | last post by:
Okay all I have a problem. I have two list of adresses and phone numbers. I do not have control over the contents of the lists The only unique field between the two is the phone number. I need to be able to inner join the two lists on phone number. This would normally be straigt forward but the problem is that they are formated different and one of them does't even have a control on the formating. *Phone numbers are US phone...
3
21028
by: Matt | last post by:
if (123 > 33) will return true and if ("123" > 33) will return true So my question is, if the above behaviors are the same?? If string is a number, and compare with another number, it will be the same behavior as compare 2 numbers?
12
29472
by: Assimalyst | last post by:
Hi, I have a working script that converts a dd/mm/yyyy text box date entry to yyyy/mm/dd and compares it to the current date, giving an error through an asp.net custom validator, it is as follows: function doDateCheckNow(source, args) { var oDate = document.getElementById(source.controltovalidate); // dd/mm/yyyy
14
8662
by: thehobbit | last post by:
Hi, Could anyone give ideas on how to add 4 20 digit numbers in ANSI C and pass the result back to a calling program in COBOL? We were able to add up to 15 digit numbers without any problems, but we started facing issues once we go above 15 digits. Thanks, Venkat
10
1524
by: agendum97 | last post by:
I have three values: UInt64 a, b, c, d; I need to determine if: (a*b) <=(c*d). Naturally, just doing the multiplication and comparing would tell me the result. However, the values could potentially overflow. For example, if: a = UInt64.MaxValue; b = 2;
7
21599
by: harijay | last post by:
Hi I am a few months new into python. I have used regexps before in perl and java but am a little confused with this problem. I want to parse a number of strings and extract only those that contain a 4 digit number anywhere inside a string However the regexp p = re.compile(r'\d{4}')
0
10330
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9952
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8976
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7500
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3654
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.