2

I've run into this problem before, but with floating point numbers. Similar to this other post. But now it's with normal numbers.

I was trying to do this:

var 
    str = 'asdf_10150663120210603',
    num = +str.split('_')[1];

console.log(num);
// 10150663120210603 expected
// 10150663120210604 actually resulting

And so I tried, in Node & Chrome Inspector, to simply output the number.

console.log(10150663120210603);
// 10150663120210604 actually resulting

Is there any crazy way, hackish or not, to make a variable equal to 10150663120210603. Or must I use strings?

Community
  • 1
  • 1
Marshall
  • 4,716
  • 1
  • 19
  • 14
  • 2
    It's the same problem, as there are *only floating point numbers* in JavaScript. – Bergi Feb 21 '12 at 02:30
  • What exactly do you want this number for? There do exist bignum libraries for JS, e.g. http://jsfromhell.com/classes/bignumber – Russell Borogove Feb 21 '12 at 02:52
  • I'm using a Node module that takes JS vars and creates an insert / replace statement. And based on the type of the variable it adjusts the statement. So a number of `123` will create something like `INSERT INTO x (n) VALUES (123)` while a string of `'123'` would result in `INSERT INTO x (n) VALUES ('123')`. Though the database is not set up to be strict, so that should fine. Strings it is. – Marshall Feb 21 '12 at 16:57

3 Answers3

3

Floating point numbers in JavaScript are 64-bit IEEE-754 floating point values. They have only 52 bits for the mantissa, and your number requires 54 bits to represent. It's just being rounded off.

If it's rounded to 10150663120210604 it can be represented in 52 bits.

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

JavaScript uses IEEE 754 double-precision floating-point format to represent all numbers and that format can represent exactly the integers up to 2^52. Since your number is larger than the largest exactly representable integer it gets rounded.

maerics
  • 151,642
  • 46
  • 269
  • 291
1

JavaScript represents numbers using IEEE-754 double-precision (64 bit) format. As I understand it this gives you 53 bits precision, or fifteen to sixteen decimal digits. Your number has more digits than JavaScript can cope with, so you end up with an approximation.

If you don't need to do any maths operations on the numbers then the easiest workaround is just to represent them as strings.

Otherwise you can use a big int library (or implement your own).

nnnnnn
  • 147,572
  • 30
  • 200
  • 241