Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Javascript from rounding big numerical IDs

Tags:

javascript

The following throws up an alert box reading: 211466719468855300. Why is this happening, even when I try casting it to a String? How can I read it accurately?

HTML:

<a class="delete-link" data-id="211466719468855298">Delete</a>​

JS:

$('.delete-link').click(function(e) {
        var $item =$(this);
        var itemID = String($item.data('id'));
        alert(itemID);
});

Fiddle: http://jsfiddle.net/zUbym/1/

like image 980
Yarin Avatar asked Jun 09 '12 15:06

Yarin


People also ask

How do you handle large numbers in JavaScript?

We can deal with large numbers in JavaScript using the data type BigInt. Advantages: It can hold numbers of large size. It perform arithmetic operations.

How do I limit the number of decimal places in JavaScript?

To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places.

How do I stop my floating from rounding?

you need to include <iomanip> and use the std::setprecision manipulator. To get the level of accuracy you want you will need to use double s rather than float s.

How do you round to 2 decimal places in JavaScript?

Use the toFixed() method to round a number to 2 decimal places, e.g. const result = num. toFixed(2) . The toFixed method will round and format the number to 2 decimal places.


1 Answers

It's happening for two reasons:

  1. jQuery does you the favor of converting your "data-" attribute values to "appropriate" types
  2. Numbers that large cannot be represented exactly in JavaScript, because all numbers are 64-bit IEEE 794 floating point values.

If you get the attribute value with ".attr()" directly, you can avoid the numeric conversion, but you'll have to keep it a string. Alternatively, you could prefix your data values with some non-digit character ("_" or whatever) to keep jQuery from trying to do you a favor.

like image 169
Pointy Avatar answered Oct 10 '22 19:10

Pointy