Hmm.. I think using Java's BigInteger from nashorn is an option.
java.math.BigInteger.valueOf(2 * 5 * 103).multiply(new
java.math.BigInteger("3030214670981671")
-Sundar
________________________________
From: nashorn-dev <[email protected]> on behalf of Bruno Borges
<[email protected]>
Sent: 02 September 2022 04:20
To: [email protected] <[email protected]>
Subject: Math exercise not computing correctly
Hey all,
I am playing with factorization, and the following problem does not eval to the
right value.
I tried the same with Node and it worked fine.
2 * 5 * 103 * 3030214670981671 = 3121121111111121130
-> https://www.wolframalpha.com/input?i=2+*+5+*+103+*+3030214670981671
Java computes the correct result: 3121121111111121130
Nashorn (v15.4) computes the following result: 3121121111111120896
Node.js (v16.14.2) computes the following result: 3121121111111121000
As you may know, this is because numbers in JavaScript are represented as
double, and then we lose precision.
The solution for Node.js, is the use of BigInt(number), or appending the letter
'n' after each number:
> 2n * 5n * 103n * 3030214670981671n
3121121111111121130n
What would be the best workaround for Nashorn?