Adamhumbug Posted July 12, 2020 Share Posted July 12, 2020 I am creating an array of numbers that i would like to add together and get a sum. JS thinks that these are string and when i try and add one to another, they get appended to the end. This is the code that i have: The second console log gives me 85.00 for example. When the code runs again i end up with 85.0085.00 function financialsReCalc(){ var transIN = document.getElementsByClassName("newTransValue"); console.log(transIN); moneyValues = []; for (i = 0; i < transIN.length; i++) { moneyValues.push(transIN[i].getAttribute('value')) } var moneyvals = moneyValues.reduce(myFunc); function myFunc(total, num) { return total + num; } console.log(moneyvals) } All i am looking to do is add up the numbers in the array Quote Link to comment Share on other sites More sharing options...
Adamhumbug Posted July 12, 2020 Author Share Posted July 12, 2020 Turns out this did it moneyValues.push(parseInt(transIN[i].getAttribute('value'))) Quote Link to comment Share on other sites More sharing options...
requinix Posted July 12, 2020 Share Posted July 12, 2020 You know how if you put numbers in a query string, like ?value=123, and you try to get it in $_GET, the value is a string? Same thing. But what you're doing to total these numbers is... silly. Why are you putting these things into an array? Using Array.reduce? All you need is simple addition. You way overthought it. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.