Sum of decimals within an array

0

I have problems adding decimals to an array.

Doing it this way:

   var array = [2.74, 48.39, 71.45, 85, 38.39];
    
    var sum  = 0;
    //console.log(array.length);
    for (var i = 0; i < array.length; i++) {
      console.log(array[i]);
      sum += array[i];
    }
    console.log(sum);

or this:

var array = [2.74, 48.39, 71.45, 85, 38.39];
let sum = array.map(c => parseFloat(c)).reduce((a, b) => a + b, 0);
console.log(sum)
  

Returns 245.97000000000003 but should be 245.97

How should you add decimals to an array?

    
asked by Carmu 20.02.2018 в 14:19
source

2 answers

0

Make use of the function .toFixed() , in this specific case .toFixed(2) will give you the result 245.97 .

  

The .toFixed() function formats a number with a specific number of digits to the right of the decimal.

Why this is , here If you want to read it, I think that the explanation goes away from the topic, since it is purely how the float type is treated computationally. PS: The article is in English unfortunately.

    
answered by 20.02.2018 / 14:33
source
-3

You have tried to format the output with number_format ($ number, 2, '.', '');

Here you have the php manual

    
answered by 20.02.2018 в 14:23