javascriptmath

Large numbers - Math in JavaScript


I'm developing a 3D space game, which is using alot of math formulas, navigation, ease effects, rotations, huge distances between planets, objects mass, and so on...

My Question is what would be the best way in doing so using math. Should I calculate everything as integers and obtain really large integers(over 20 digits), or use small numbers with decimals.

In my experience, math when using digits with decimals is not accurate, causing strange behavior when using large numbers with decimals.


Solution

  • I would avoid using decimals. They have known issues with precision: http://floating-point-gui.de/


    I would recommend using integers, though if you need to work with very large integers I would suggest using a big number or big integer library such as one of these:

    The downside is you have to use these number objects and their methods rather than the primitive Number type and standard JS operators, but you'll have a lot more flexibility with operating on large numbers.

    Edit:
    As le_m pointed out, another downside is speed. The library methods won't run as fast as the native operators. You'll have to test for yourself to see if the performance is acceptable.