0

Tried this in node v0.8.15 and firebug:

(123123123123123123123).toString(10)

Result: '123123123123123130000'

Anyone know what's going on?

ibash
  • 1,477
  • 17
  • 31
  • 1
    Floating point numbers has limited precision. – Dmitry Manannikov Aug 26 '13 at 20:51
  • 1
    i'm guessing its something to do with integer overflow. A quick google search shows that `9007199254740992` is the maximum int value in javascript without loss of precision. – underbar Aug 26 '13 at 20:53
  • 1
    @underbar: Nope. There are no integers in JavaScript (unless in bitwise operations), and no overflows therefore. – Bergi Aug 26 '13 at 20:56
  • Note that it is not `.toString()` that is changing your number: JS has limited precision for numbers no matter what operation you perform on them. – nnnnnn Aug 26 '13 at 20:59
  • @Bergi Ahhh thanks for the insight. Never even occurred to me that what I assumed were ints were actually precise floats. – underbar Aug 26 '13 at 21:07

2 Answers2

2

JavaScript stores numbers as 64-bit floating-point IEEE 754 values, so the maximum precision is 2^53 (9007199254740992). Anything beyond that, and the least-significant digits are just set to 0.

For example:

(9007199254740992).toString()    // 9007199254740992
(90071992547409925).toString()   // 90071992547409920
(900719925474099255).toString()  // 900719925474099200
// etc

If you really need that many digits of precision, you should look into a library such as bignum (the author helpfully lists other such libraries).

Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
2

All numbers in javascript (unlike many other languages) are stored as (AFAIK 64-bit) floating-point numbers (never integers).

If you're not familiar with how this works, it is like scientific notation (AKA standard form): a * 10b

When you type 123123123123123123123, it is too big to fit in the a part of the float. The value of a will be stored as 1.2312312312312313, truncating the lowest-value overflowing digits, and b is set to 20 to provide an approximation as good as possible of the original value. When you get the string value, 1.2312312312312313 * 1020 is calculated, giving 123123123123123130000.

Matt Randell
  • 374
  • 1
  • 3
  • 11