0

I have a JSON object which contains id and price.

Suppose the maximum length "price" field can hold is of 18 digits.

Now I want to print the id and price but whenever I am printing the price, I'm not getting the actual price value.

Later I came to know that Numbers in JavaScript have limited precision having max size 2**53-1.

I also tried using BigInt because of big size of price field but no luck. like :- alert(BigInt(data.programs[0].price));

How can I display the price field value correctly?

$(document).ready(function() {             
  var data = { "programs": [ { "id":100, "price":123456789123456789 }, { "id":200, "price":123456789987654321 } ] };
  $.each(data.programs, function (i) {
    $.each(data.programs[i], function (key, val) {
      alert(key +" : "+ val);
    });
  }); 
}); 
ClickThisNick
  • 5,110
  • 9
  • 44
  • 69
Sam
  • 1
  • 2
  • 3
    You can use `BigInt`, but only if the JSON object can pass the value of `price` as a _string_. As long as it's a number, you're out of luck. – robertklep Jan 12 '19 at 20:08
  • You can't parse a JSON with a big number directly, you'll need to extract the string manually somehow. You might be interested in [this](https://stackoverflow.com/questions/18755125/node-js-is-there-any-proper-way-to-parse-json-with-large-numbers-long-bigint) – najayaz Jan 12 '19 at 20:09
  • @robertklep :- This issue is bcoz the price field is number. If it would have been a string, I wouldn't have posted this question. – Sam Jan 12 '19 at 20:21
  • If you can't control the JSON, you have to resort to the method suggested in the answer for the question that @G-man links to. – robertklep Jan 12 '19 at 20:25
  • 1
    Related: https://stackoverflow.com/questions/13502398/json-integers-limit-on-size – Barmar Jan 12 '19 at 20:52

0 Answers0