# Using java.math.BigInteger in Nashorn / jjs?

Roland Bouman roland.bouman at gmail.com
Tue Dec 29 01:53:41 UTC 2015

```Hi all,

I'm new to this list - apologies if this topic came up earlier,

I'm trying to work use java,math,BigInteger in my javascript - obviously to
overcome the limitations of the JavaScript built-in Number type.

Please consider the concrete example of a Java function I would like to get
working in Nashorn / jss javascript below:

public static BigInteger fibonacci(int n) {
BigInteger prev = new BigInteger("0");
if (n == 0) {
return prev;
}
BigInteger next = new BigInteger("1");
if (n == 1) {
return next;
}
BigInteger fib = null;
int i;
for (i = 1; i < n; i++) {
prev = next;
next = fib;
}
return fib;
}

We can test with these values:

n=77: 5527939700884757
n=78: 8944394323791464
n=79: 14472334024676221

So far so good. Now I try the - what I think is - equivalent function in
javascript:

function fibonacci(n) {
var BigInteger = Java.type("java.math.BigInteger");
prev = new BigInteger("0");
if (n == 0) return prev;

next = new BigInteger("1");
if (n == 1) return next;

var i, fib = null;
for (i = 1; i < n; i++) {
prev = next;
next = fib;
}
return fib;
}

However, now we get different results:

n=77: 5527939700884757
n=78: 8944394323791464
n=79: 14472334024676220

Note that the value for n=79 is off by one.

What I suspect happens is that the next passed to .add gets first evaluated
and then silently cast to a javascript Number type before it is actually
passed into add (at which point it will probably need to be converted to a
BigInteger again) but then it will have lost its precision already.

A simpler example can be shown here:

var str, BigInteger = Java.type("java.math.BigInteger");
str = "9999999999999998";
print(str + ": " + (new BigInteger(str)).toString());
str = "9999999999999999";
print(str + ": " + (new BigInteger(str)).toString());

outputs:
9999999999999998: 9999999999999998
9999999999999999: 10000000000000000

(whereas in java the ouput checks out as expected)

Is there anything I can do to make BigInteger additions work in jss /
Nashorn javascript code?

--
Roland Bouman
blog: http://rpbouman.blogspot.com/