Thursday, 13 July 2017

Division inaccurate in Javascript?











If I perform the following operation in Javascript:



0.06120*400



The result is 24.48.



However, if I do this:



24.48/400


The result is:




0.061200000000000004


JSFiddle: http://jsfiddle.net/zcDH7/



So it appears that Javascript rounds things differently when doing division and multiplication?



Using my calculator, the operation 24.48/400 results in the correct answer of 0.0612.



How should I deal with Javascript's inaccurate division? I can't simply round the number off, because I will be dealing with numbers of varying precision.




Thanks for your advice.


Answer



You can get the correct result with simply using:



var a = 24.48/400;
console.log(a.toFixed(6));


And because typeof a.toFixed(6) === 'string' you can:




var a = 24.48/400;
console.log(parseFloat(a.toFixed(6)));



  • The argument of toFixed is the number of decimals you want.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...