0

I am making an ajax call to a web service and fetching JSON data which contains decimal properties.

Issue:

When I see values on the server-side before returning and browser network tab response for the request both have the value which does not match with inspecting of the success callback of jQuery ajax call.

Differences:

Original Value       : 5.74999999999999999999999999    
Ajax success callback: 5.75    
Original Value       : 465.90909090909090909090909088    
Ajax success callback: 465.90909090909093

Note: I am not doing any calculations in javascript. Just trying to display.

I tried to parse JSON using JSON.parse which will parse correctly. I think there is some issue with the jQuery library itself where JSON response is converted javascript object. Is there any way to correct this behavior.

Additional Info:

An experiment not exactly relevant to the question because the calculation is not being done in the javascript side.

Interestingly value is not correct in Windows Calculator, Google Search, Browser console.

(37.272727272727272727272727270 *522.5)/100 = 194.75 instead of 4.7499999999999999999999

Any clarifications on this would be appreciated.

With regards, Nithin B.

Nithin B
  • 601
  • 1
  • 9
  • 26
  • how many decimal points do you want? – Able Alias Jul 09 '20 at 10:51
  • 1
    JS has problems with floating point numbers. For example, try adding `0.1 + 0.2` in your browser console. Send it as string from the backend to prevent JS from ruining the value. Or try something like this: https://stackoverflow.com/questions/11695618/dealing-with-float-precision-in-javascript – cloned Jul 09 '20 at 11:22
  • I want to display exact number without any rounding. It looks like some issue with JS or jQuery. Because I am not calculating anything in JS. Just display. JSON.parse shows the correct number. Actually it seems the issue is 9999999. Number 465.90909090909090909090909088 is coming as 465.90909090909093. Not sure what is jQuery doing internally. Updating question with this info too. – Nithin B Jul 09 '20 at 11:36
  • Send it as a string nog a number. – Grumpy Jul 09 '20 at 11:47
  • It would be nice to know what happens here. Is it a bug or not. If it's not a bug then what's the concept behind it. I am expecting the numbers to behave as I do manually on paper. In C# it works exact as I want. But in JS it doesn't. Any links where the calculation under the hood is explained for his behaviour? – Nithin B Jul 09 '20 at 11:58

0 Answers0