PHP FIX IssuesCategory: JavascriptSum of string decimals – JavaScript
comcoachi asked 48 years ago

How to iterate the array and get the sum of them. i have add array of string that are decimals. For example :


function check() {
    let arr = ["1,50", "1,50"];
    let sum1 = 0;
    let sum2 = "0";
    let sum3 = 0

    for (let i = 0, length = arr.length; i < length; i++) {
       sum1 += +arr[i];
       sum2 += +arr[i];
       sum3 +=  arr[i];  

    }
    console.log(sum1, sum2, sum3)
    //sum1 = NaN
    //sum2 = '0NaNNaN'
    //sum3 = 01,501,50
}
1 Answers
Laxmi Kant answered 6 months ago

You can use reduce() for sum and replace() to replace , with ..

let arr = ["1,50", "1,50"];
const result = arr.reduce((r, e) => r + +e.replace(',', '.'), 0)
console.log(result)

Author - comments - 0

Copyright © 2018 - Designed by HTML Design