Search code examples
javascript64-bitecmascript-next

Native support for 64 bit floating point in Javascript


As the question here states, even the newest Ecmascript 8 has no support for 64bit integers.

But the stage 3 proposal for bigInt looks promising and I expect it will be added to the Js spec sometime soon.

However, Even according to the proposal, we have to use a special constructor for declaring big numbers. (Q1) What is the technical reason behind, being unable to represent big numbers in the general way?

let bigNum = 2 ** 64 // Why can't JS do this without losing precision? (at least in future)

I know that JavaScript represents all numbers using IEEE-754 double-precision (64 bit) floating points and that this causes the problem.

(Q2) Why can't Javascript represent all numbers using some other standard which doesn't lose precision?

(Q3) What complications would arise if Javascript actually did that?

Edit: As stated by T.J, we can use a suffix instead of a constructor, but I still feel that is not exactly the general notation


Solution

  • (Q1) What is the technical reason behind, being unable to represent big numbers in the general way?

    Breaking the web. The fundamentals of JavaScript numbers cannot be changed now, 20-odd years after they were originally defined. There's also the issue of performance: JavaScript's current numbers (IEEE-754 binary double [64-bit] precision) are very fast floating point thanks to being built into CPUs and math coprocessors. The cost of that speed is precision; the cost of arbitrary precision (or a dramatically larger precise range) is performance.

    Someday in the future, perhaps JavaScript will get IEEE-754 64-bit or even 128-bit decimal floating point numbers (see here and here), if those formats (introduced in 2008) diffuse into the ecosystem and get hardware support. But that's speculation on my part. :-)

    (Q2) Why can't Javascript represent all numbers using some other standard which doesn't lose precision?

    See Q1. :-)

    (Q3) What complications would arise if Javascript actually did that?

    See Q1. :-)

    Even according to the proposal, we have to use a special constructor for declaring big numbers.

    If you want 64-bit specifically. If you just want BigInts, the proposal includes a new notation, the n suffix, for that: 2n is a BigInt 2. So with BigInts, your example would be

    let bigNum = 2n ** 64n;