Big JavaScript ints won't cast to String without rounding

262 views Asked by At

I am trying to pass a big int to a function from an onclick event in HTML. The ints are always very long, and I cannot seem to pass it to my function without rounding. I have tried some bigInt libraries to the same end, though I would much rather prefer simple string casting.

My js function:

    function initBuy(id){
      console.log(id.toString());
    }

and my HTML event:

<dt></dt><dd><a id="buy" onclick="initBuy(String(' + all_data[index].listing_id + '))" class="btn btn-success">Buy This Item</a></dd>

An example of a passed int:

13934317650292905813

and the result of clicking the button:

"13934317650292906000"

The passed int looks fine when I write it to an elements' text. When I pass it to a function, however, it's rounding it.

2

There are 2 answers

0
GitaarLAB On BEST ANSWER

You say in your (ambiguous) question:

'The passed int looks fine when I write it to an elements' text. When I pass it to a function, however, it's rounding it.'

and in your comment:

If I set all_data[index].listing_id to an elements text, it works.

That means you are already getting the 'integer' as text-string in JSON.

Nothing in your current question converts the string to a number (I tested it).
As soon as the string would be converted to a number it would overflow IEEE 754's max accuracy of 2^53=9007199254740992.

Note that: initBuy(String(' + all_data[index].listing_id + '))
will return the string + all_data[index].listing_id + (as it should).

Passing the string '13934317650292905813' to your initBuy function also returns string '13934317650292905813' (as it should).

In other words, I can not reproduce your problem using the code you have supplied.

I assume you have simplified your initBuy function for this question (you'd have to post the original one for further examination, preferably together with an excerpt of a relevant part of the raw JSON string).

I assume you might accidentally convert the string to a number (probably using a +) inside that function!

1
Rama Kathare On

From the post here the maximum value an integer in Javascript could take is 9007199254740992

Your number 13934317650292905813 is far bigger than that.

From this post here you can use BigInteger.js to accommodate big integers