4

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?

Zach
  • 5,715
  • 12
  • 47
  • 62

3 Answers3

2

MathUtils

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

console.log(MathUtils.roundToPrecision(0.3 + 0.6, 1)) // 0.9;
Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47
0

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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
Jos de Jong
  • 6,602
  • 3
  • 38
  • 58