0

I am passing the exact Id (i.e. 123456789123456.99) from controller in JSONResult, but when I get the value in AJAX response I get Id (i.e. 123456789123456.98).

I have observed a weird behavior in JavaScript while parsing data. Please look into the below image. Can anyone please help me here to get the same Id after parsing through JSON.

enter image description here

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Ronak
  • 127
  • 3
  • 15
  • Wouldn't a string do? – Teemu Aug 31 '17 at 11:25
  • Welcome to the world of floating point numbers, .. It's not a JSON problem either.. For better handling of large numeric numbers, there are a number of BCD implementations in javascript that you might want to look into. – Keith Aug 31 '17 at 11:25
  • I believe this has to do with floating point inaccuracy, take a look at https://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples – Mike Aug 31 '17 at 11:26
  • Perhaps this would be helpful: https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – yezzz Aug 31 '17 at 11:26
  • @Keith - Can you please provide me the link of BCD implementation in JS and the way to resolve my issue. – Ronak Aug 31 '17 at 11:54
  • Are you requiring to do math's equations on these numbers, if yes, use http://mathjs.org/index.html they have a BigNumber implementation. Inside the JSON though, you will want to store as string like others have said. – Keith Aug 31 '17 at 12:01
  • May be this will be helpful: https://www.npmjs.com/package/big-integer – Vyacheslav Aug 31 '17 at 12:14

1 Answers1

2

The Id value is too big. JavaScript uses double-precision floats for numbers, and they have about 15 digits of precision. The highest integer that JavaScript can reliably save is something like 2^51. That is why the value get rounded when you parse.

However, you can work around this limitation by sending the number as a string like so:

var res = '{"Id":"123456789123456.99"}';
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
  • I don't want to add new property with string in my model. Is there any other resolution? – Ronak Aug 31 '17 at 11:53