9

I set up a system that parses a compact data string into JSON. I'm using a 19 digit number to store ids. Unfortunately any number greater than 17 digits, parseFloat() rounds the last few digits.

This breaks the whole data string. Can I fix this?

For example 8246295522085275215 gets turned into 8246295522085276000. Why is this?

http://jsfiddle.net/RobertWHurst/mhZ7Q/

alex
  • 479,566
  • 201
  • 878
  • 984
Robert Hurst
  • 8,902
  • 5
  • 42
  • 66
  • You don't have that many objects, right? Then use regular incrementing IDs starting with `1`. If you want to prevent people from being able to retrieve other objects by changing the ID, add an additional argument containing some random value - then you can still use a proper ID (also in your database as the primary key) and when a user tries to modify the URL he's out of luck since he doesn't know the random string of other items. – ThiefMaster Nov 03 '11 at 00:04
  • 1
    if this is an id why bother treating it as a number at all? just keep it as a string – jk. Nov 03 '11 at 10:54

3 Answers3

12

JavaScript has only one numeric type, which is an IEEE 754 double precision floating-point. That means, you have a maximum of 52 bits of precision, which is a bit more than 15 decimal places.

If you need more precision than that, you have to use a bignum library or work with strings.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
3

Numbers in JavaScript lose precision if they are higher than a certain value.

According to http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference, integers are only reliable up to 15 digits (9 * 10^15 to be exact).

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

Try one of these 1. Use a string 2. Split your number in two and save the smaller parts to an array 3. Bignum library 4. Use a smaller number if you can

Emanual
  • 11
  • 1