How do I fix 0.3 + 0.6 = 0.89999999999 in Javascript?

When I add two float values, I get something like:

0.3+0.6 = 0.89999999999 

      

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

+3


source to share


3 answers


MathUtils



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

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

      

+1


source


Essentially the same way, but JavaScript has no built-in type decimal

. If you are looking, you can find various implementations such as big.js

(just an example, not a recommendation).



0


source


Use the BigNumber library. For example math.js has support for bignomes (powered by decimal.js ).

Using the math.js expression parser, you can inject natural expressions using bignomes:

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

      

0


source







All Articles