Why is it that adding two values to decimals is not accurate?

2

I'm trying to sum two values with decimals of two variables:

valor1 = 10.00;
valor2 = 10.99;
console.log(valor1+valor2);

Adding the two values returns 20.990000000000002 and not 20.99 .

When I add values with nonzero decimals, the result is accurate, for example:

valor1 = 10.03;
valor2 = 10.81;
console.log(valor1+valor2);

Why is the result of the first example not accurate?

    
asked by anonymous 02.02.2018 / 05:40

3 answers

2

It is because there is no way to accurately represent 20.99 with a floating-point number. It's not just in javascript that has this side effect, all languages that use some kind of floating point suffer from the same problem.

You can, in this specific case, use the toFixed to show only the 2 desired homes:

valor1 = 10.00;
valor2 = 10.99;
console.log((valor1+valor2).toFixed(2));
    
02.02.2018 / 06:11
0

Try using toFixed ():

<script>
  var valor1 = 10.00;
  var valor2 = 10.99;
  var soma = ( valor1 + valor2 );
  console.log(soma.toFixed(2));
</script>

Reference: link

var valor1 = 10.00;
var valor2 = 10.99;
var soma = ( valor1 + valor2 );
console.log(soma.toFixed(2));
    
02.02.2018 / 06:13
0

I think it's better to do rounding, tofixed may not give the expected value.

function myRound(val, dec) {
    return (Math.round(val*Math.pow(10,dec))/Math.pow(10,dec)).toFixed(dec);
}

var valor1 = 10.00;
var valor2 = 10.99;
var soma = ( valor1 + valor2 );
soma = myRound(soma, 2);
    
02.02.2018 / 10:16