Thursday, 22 March 2018

math - How to fix 0.3+0.6=0.89999999999 in Javascript?




When adding two float values, I will get something like:



0.3+0.6 = 0.89999999999 


I know what's going on. In C# we can use decimal instead, but in Javascript, how to fix it?


Answer



MathUtils




MathUtils = {
roundToPrecision: function(subject, precision) {
return +((+subject).toFixed(precision));
}
};

console.log(MathUtils.roundToPrecision(0.3 + 0.6, 1)) // 0.9;

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...