Paulius
Paulius

Reputation: 99

Jquery, how to work with high numbers

I need to validate some integer number which is 22 chars long. I need to divide that number and get quotient as well as remainder of divining. BUT, when I send it to modulo function, it returns 7.04406000774059e+21

labas = modulo(7044060007740589212932, 97);
function modulo (divident, divisor){
alert(divident);
}

Upvotes: 0

Views: 1915

Answers (2)

Robert Lozyniak
Robert Lozyniak

Reputation: 322

I think you mean divide (not "divine") and remainder (not "bad part").
I rolled some funny dice to get a random number (8233), which I will use for some examples.
* When you divide 8233 by 8, the remainder is 1. 8233 = (8 * 1029) + 1
* When you divide 8233 by 9, the remainder is 7. 8233 = (9 * 914) + 7
* When you divide 8233 by 10, the remainder is 3. 8233 = (10 * 823) + 3
* When you divide 8233 by 11, the remainder is 5. 8233 = (11 * 748) + 5

To answer your question:
When dealing with numbers in JavaScript, you must remember that only the first fifteen or sixteen digits are good. If the number has more digits, the results usually will not be exact.
Your example uses this number: 7044060007740589212932 JavaScript cannot deal with that number exactly. The best it can do is 7044060007740589735936, which is 523004 too high. But you don't want 7044060007740589735936, you want 7044060007740589212932.
Here is a workaround:
Keep your number as a string, not as a number.
"7044060007740589212932"
Then separate the string into two parts, right in the middle.
"70440600077" and "40589212932"
Now you have two strings, each containing eleven digits.
Then do this:
parseInt("70440600077", 10) gets you the number 70440600077
(70440600077 % 97) gets you the number 36
Notice that (97 * 726191753) + 36 = 70440600077
Then take the 36 and do this:
(36 + "40589212932") gets you the string "3640589212932"
(A number plus a string does a string concatenation.) parseInt("3640589212932", 10) gets you the number 3640589212932 (3640589212932 % 97) gets you the number 0, which is your end result. Notice that 97 * 37531847556 = 3640589212932 exactly.

72619175300000000000 * 97 =  7044060004100000000000
         37531847556 * 97 =           3640589212932
====================         ======================
72619175337531847556 * 97 =  7044060007740589212932

And there you go.

Upvotes: 0

Dziad Borowy
Dziad Borowy

Reputation: 12579

There are a couple of libraries for handling big numbers in js:

Upvotes: 1

Related Questions