Issue with jQuery data() treating string as number

I have a MySQL BIGINT that I am storing in HTML5 data. Then I'm trying to access that value and pass it through an AJAX call.

<div data-id="211285677671858177">

And the JavaScript:

var send_data = {
    id: '' + $(this).data('id')
$.post('/send.php', send_data);

The issue is that the jQuery data function seems to retrieve that value as a floating point and not a string. So appending it to a blank string isn't helping because it's already too late - it's already been rounded (in this case to 211285677671858180). What can I do to fix this?


This isn't a case of "long int" really, the number you're getting is the closest available representation as a floating-point number.

Anyway, you want the value as a string. Quote the jQuery docs for .data (emphasis mine):

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.

There's no such thing as a "long integer" in JavaScript. All numbers are 64-bit floating point. Your number there cannot be represented exactly in IEEE-794 floating point representation.

The only way to "fix" this is to make the number into a string in a domain that can cope with big integer values.

try typecasting it to string:

id: '' + $(this).data('id').toString();

Try surrounding the data attribute value in single quotes, if you want data to treat it like a string. Problem there, I guess, is you'll have the quotes to strip.

I had a similar issue where the data id (alphanumeric) was getting converted through usage of .data() as a result the last few characters were getting converted to all zeroes. It took some research to determine that this is a bug in jQuery implementation of .data().


For me, to get the data id directly as a work around, I used .attr("data-id") directly and this gave me the correct id.

Need Your Help

How do I store and retrieve credentials from the Windows Vault credential manager?

security winapi authentication credentials dpapi

I want to securely store a plaintext password on Windows PC. I am currently using DPAPI CryptProtectData to encrypt it, then store the encrypted blob in a file in user's local AppData.

Click event on dynamic element WITHOUT jQuery

javascript dom

I would like add an event such as onclick or mouseover to a dynamically created element (similar to the .live function in jQuery) do I do this using pure javascript without a framework such as