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?
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?
MathUtils = {
roundToPrecision: function(subject, precision) {
return +((+subject).toFixed(precision));
}
};
console.log(MathUtils.roundToPrecision(0.3 + 0.6, 1)) // 0.9;
Essentially the same way, but JavaScript doesn't have a decimal
-like number type built in. If you search, you can find various implementations like big.js
(just an example, not a recommendation).
Use a BigNumber library. For example math.js has support for bignumbers (powered by decimal.js).
Using the expression parser of math.js, you can type natural expressions using bignumbers:
// configure math.js to use bignumbers
math.config({number: 'bignumber'});
// evaluate an expression
math.eval('0.3 + 0.6'); // returns a BigNumber with value 0.9