1

In JavaScript, when I do a calculation with very large numbers (example: Math.pow(4,2015)*Math.pow(9,2016)), it returns infinity.

Is there anyway to prevent getting infinity and get the actual result?

Pang
  • 9,564
  • 146
  • 81
  • 122
Mykybo
  • 1,429
  • 1
  • 12
  • 24
  • 2
    You'll have to use a "bignum" library. See http://stackoverflow.com/questions/3072307/is-there-a-bignum-library-for-javascript – Ethan Brown Apr 10 '15 at 22:50
  • @EthanBrown Well, I was hoping to do it with pure js.. but oh well. – Mykybo Apr 10 '15 at 23:00
  • 2
    Well, short of re-writing a bignum library, you can't do it with "pure JS." Numbers in JavaScript are IEEE-754 double-precision floating-point numbers. It's the same in most languages (except most other languages have an integer type), so this isn't a limitation of JS per se. – Ethan Brown Apr 10 '15 at 23:15
  • Depending on your application, you might be able to leverage the rules of logarithms to do the heavy lifting, then convert to big numbers. For example, if you take the ln of 4^2015*9^2016, you get 2015*ln(4) + 2016*ln(9), which are much more reasonable numbers to deal with. Then just raise e to the result, and you "recover" your original result. – Ethan Brown Apr 10 '15 at 23:20
  • Related: [What's a good way to store extremely large numbers? (Eg. 572e6561) in C#](http://stackoverflow.com/q/29380861/1468366) – MvG Apr 11 '15 at 00:41

0 Answers0