Arbitrary precision numbers and Javascript, Google Web Toolkit

288 views Asked by At

This is not really a question as I do have a work around with the issue, but I thought I'd let everyone know because it may have quite a wide impact on the way people work with the Google Web Toolkit.

So one of the problem is with the way Google gson represents numbers in JSON. For example, int myInt = 2 will become "myInt":2 and long myLong = 5432198765L will become "myLong":5432198765, and BigInteger myBI = 1310381093810938109481049128409487109378109248104098130981039810983 will become "myBI":1310381093810938109481049128409487109378109248104098130981039810983. While gson itself can deserialize this without a problem, the AutoBeans framework in GWT 2.4 in JSON will not like it. Issue 6331 fixes it for the long representation in the upcoming GWT 2.5 release. However, issue 7555 will not be resolved because of the way Javascript number precision works.

Thus, we will need to represent BigIntegers as Strings and it will work, e.g., String myBIStr = new BigInteger("1310381093810938109481049128409487109378109248104098130981039810983").toString() will be represented as "myBIStr":"1310381093810938109481049128409487109378109248104098130981039810983". At the GWT end, this will result a String and we will have to build a BigInteger out of it.

It all makes perfect sense why Google will not resolve 7555, but that leads me to the real open question: how does one deal with high precision numbers in Javascript?

In general, if web-based Javascript and Google Web Toolkit front-ends are to challenge native front-ends, then there could be situations where we work with arbitrary precision numbers, instead of being restricted by about the 53-bit precision that comment 3 talks about. What's even worse is that doesn't this limitation also affect node.js or any other server side Javascript?

Is there a nice work around, especially one that uses or seamlessly works with Google Web Toolkit?

1

There are 1 answers

4
Riley Lark On

GWT can do math on integers wider than 53 bits because it emulates Long (and BigInteger I think). The math is slower, since it can't just use the native JS operations, but there's not a hard limit.

So, GWT has already implemented the workaround, and it's built in. You just have to avoid passing numeric JSON when you need a big integer.