Jump to content

JS think my decimal is a string


Adamhumbug

Recommended Posts

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

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.