how to sum integer from htmlelement - javascript

I am trying to get the innerHTML of all elements with classname "money" and sum it. But when I am retrieving it with my code it will place all the digits next to eachother.
var elements = document.getElementsByClassName("money");
var arr = new Array(elements.length);
var total = 0;
for (var i=0; i< arr.length; i++){
var val = elements[i].innerHTML;
console.log(val);
total += parseFloat(val).toFixed(2)
}
console.log(total);
The result I'm getting is the following:
image of result
How can I solve this?

toFixed() is converting a number to a string. So you add strings which leads to concatenating.
Sum everything and use toFixed() after you have the final value or use Math.round()

toFixed() returns a string. Parse it (with a unary plus operator), then add to total:
var elements = document.getElementsByClassName("money");
var arr = new Array(elements.length);
var total = 0;
for (var i = 0; i < arr.length; i++) {
var val = elements[i].innerHTML;
console.log(val);
total += +parseFloat(val).toFixed(2)
}
console.log(total);
<div class="money">100</div>
<div class="money">200</div>
<div class="money">300</div>

Related

Sum and Average of a series of numbers inputed to a text field

I am trying to create an application that calculates the sum and average of numbers that are inputted into a text field separated by spaces.
I am stuck on the part where you have to put in a loop to calculate the sum and avg from the spaced inputs. I have been using console.log to test throughout while I type my code.
Any guidance would be helpful. First time doing javascript. I have looked at the forms on this website and it seems like all the sum/avg javascript questions arent input text based. That is why I am creating a new question.
HTML and Javascript is Below
<body>
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>
</body>
Javascript
function calculateSumAverage() {
//grab the input
var numberSeries = document.getElementById("numberSeries").value;
//split it using.split(" ")
var arr = numberSeries.split(" ");
//set sum var to 0
var sum = 0;
//set avg var to 0
var avg = 0;
//loop input array and sum
for (var i=0; i<arr.length; i++){
sum += arr[i];
}
console.log(sum);
//divded by
//calculate avg divided by myarray.length
//output to div
}
// Here is your function:
/*function calculateSumAverage() {
//grab the input
var numberSeries = document.getElementById("numberSeries").value;
//split it using.split(" ")
var arr = numberSeries.split(" ");
//set sum var to 0
var sum = 0;
//set avg var to 0
var avg = 0;
//loop input array and sum
for (var i=0; i<arr.length; i++){
sum += arr[i];
}
console.log(sum);
//divded by
//calculate avg divided by myarray.length
//output to div
}*/
// Here is a way to do it functionally:
function calculateSumAverage() {
// This is the string that contains the numbers separated by a space.
var inputValue = document.getElementById('numberSeries').value;
var values = inputValue.split(' ')
.map((val) => parseInt(val))
.filter((val) => !isNaN(val));
var sum = values.reduce((currentVal, nextVal) => currentVal + nextVal, 0);
document.getElementById('calculationOutput').innerHTML = `Average: ${sum / values.length}`;
}
<body>
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>
</body>
You code is fine except sum += parseInt(arr[i]); you need to parse each string input to integer
input type="text" will give a string.Also to split this string ,use var arr = numberSeries.split(""); , note there is no space between the quotes. To convert each string to number use unary operator.
sum += +arr[i]; The plus(+) sign before arr[i] will convert a string to number.Unless you convert to number , the string concatenation will produce like this 0123...
function calculateSumAverage() {
//grab the input
var numberSeries = document.getElementById("numberSeries").value;
//split it using.split(" ")
var arr = numberSeries.split("");
//set sum var to 0
var sum = 0;
//set avg var to 0
var avg = 0;
console.log(arr)
//loop input array and sum
for (var i = 0; i < arr.length; i++) {
sum += +arr[i];
}
console.log(sum);
}
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>
Try like this
function calculateSumAverage()
{
var numberSeries = document.getElementById("numberSeries").value;
var arr = numberSeries.split("");
var sum = 0;
var avg = 0;
for (var i = 0; i < arr.length; i++)
{
sum += parseInt(arr[i]);
}
}

Calculate the sum of multiple currency formatted elements

I am trying to create a sub-total based on a series of currency formatted numbers but am struggling converting the numbers back to integers so that they can be added. Here's what I have tried:
$(function() {
var totals = $('.price');
var sum = 0;
for (var i = 0; i < totals.length; i++) {
//strip out dollar signs and commas
$(totals[i].text()).replace(/[^\d.]/g, '');
//convert string to integer
var ct = parseFloat($(totals[i].text()));
sum += ct;
}
console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$195,000.20</div>
<div class="price">$21,404.00</div>
<div class="price">$7,000.00</div>
<div class="price">$450.00</div>
replace() doesn't modify the string passed in (and it couldn't here anyway, since it's the result of a function). It just returns the modified value.
Save the result of replace(), and sum based on that:
$(function() {
var totals = $('.price');
var sum = 0;
for (var i = 0; i < totals.length; i++) {
//strip out dollar signs and commas
var v = $(totals[i]).text().replace(/[^\d.]/g, '');
//convert string to integer
var ct = parseFloat(v);
sum += ct;
}
console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$195,000.20</div>
<div class="price">$21,404.00</div>
<div class="price">$7,000.00</div>
<div class="price">$450.00</div>
Also: note the typo -- you want $(totals[i]).text(), not $(totals[i].text())

Sum totals within an Array using JavaScript

When calculating values within an Array I am getting this: total = "0212.16967.04".
The correct total in this example is:1179.20
function calculateSum(){
//build array of numbers
amtArray = [];
$('.amount').each(function (index, value) {
amtArray.push($(this).text()||0);
});
//calculate all values and return results
var sum = sumArray(amtArray);
console.log('sum ->', sum)
}
function sumArray(input) {
var total = 0;
for (idx=0; idx <= input.length-1; idx++) {
total += input[idx];
}
return total;
}
calculateSum()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="amount">212.16</div>
<div class="amount">967.04</div>
Should output: 1179.20
You need to cast the value from string to number with an unary plus + (or by using Number or parseFloat, or any other operator which expects a number), otherwise if any of the operands is a string, all parts are treated as string and concatinated.
total += +input[idx];
// ^
The error here is you are concatenating strings, here's a solution:
var array = ["212.16", "967.04"]
function sumArray(input) {
var total = 0;
for (idx = 0; idx <= input.length - 1; idx++) {
total += parseFloat(input[idx]);
}
return total;
}
console.log(sumArray(array));
In the function sumArray you can directly return the result of Array.prototype.reduce() using Number to work with numerical values:
const sumArray = arr => arr.reduce((a, b) => a + Number(b), 0);
console.log(sumArray(["212.16", "967.04"]));
You are concatenating string values rather than adding flowing pointing numbers. You can use parseFloat() to convert from string to float like this this:
function sumArray(input) { //input = (2) ["212.16", "967.04"]
var total = 0;
for (idx=0; idx <= input.length-1; idx++) {
total += parseFloat(input[idx]);
}
return total;
}
Aside from using a unary, parsefloat, Number you should also use toPrecision to get that last zero you indicated in your question
var val = document.getElementsByClassName('amount');
function calculateSum() {
var total = 0;
for (var i = 0; i < val.length; i++) {
var value = val[i].textContent;
total += +value;
}
return total.toPrecision(6);
}
val[1].insertAdjacentHTML('afterend', calculateSum());
<div class="amount">212.16</div>
<div class="amount">967.04</div>

How do I add values of a prompt together?

I'm supposed to prompt the user to enter a string of numbers separated by spaces and alert the sum of those numbers. I'm trying to get the values into an array and then add them up, but it's not working. I've tried a ton of different ways. Help please!
var input = prompt("Enter a string of numbers separated by spaces");
var numbers = new Array (input.split(" "));
var sum = 0;
for(var i = 0; i < numbers.length; i++){
sum += numbers[i];
};
alert(sum);
JSFiddle: http://jsfiddle.net/mUqfX/2/
You're close, 2 issues with your code. First, .split returns an array so you don't need to wrap a new around it. Second, you need to parse the number otherwise your joining strings together. Try
var input = prompt("Enter a string of numbers separated by spaces");
var numbers = input.split(" ");
var sum = 0;
for(var i = 0; i < numbers.length; i++){
sum += parseInt(numbers[i]);
};
alert(sum);
You have 2 problems:
input.split(" ") returnss an array, so you don't need to place it in another array
Your numbers array contains strings, which you need to coerce to numbers to total them.
Try this:
var input = prompt("Enter a string of numbers separated by spaces");
var numbers = input.split(" ");
var sum = 0;
for(var i = 0; i < numbers.length; i++){
sum += parseInt(numbers[i]);
};
alert(sum);

how to add array element values with javascript?

I am NOT talking about adding elements together, but their values to another separate variable.
Like this:
var TOTAL = 0;
for (i=0; i<10; i++){
TOTAL += myArray[i]
}
With this code, TOTAL doesn't add mathematically element values together, but it adds them next to eachother, so if myArr[1] = 10 and myArr[2] = 10 then TOTAL will be 1010 instead of 20.
How should I write what I want ?
Thanks
Sounds like your array elements are Strings, try to convert them to Number when adding:
var total = 0;
for (var i=0; i<10; i++){
total += +myArray[i];
}
Note that I use the unary plus operator (+myArray[i]), this is one common way to make sure you are adding up numbers, not concatenating strings.
A quick way is to use the unary plus operator to make them numeric:
var TOTAL = 0;
for (var i = 0; i < 10; i++)
{
TOTAL += +myArray[i];
}
const myArray = [2, 4, 3];
const total = myArray.reduce(function(a,b){ return +a + +b; });
Make sure your array contains numbers and not string values. You can convert strings to numbers using parseInt(number, base)
var total = 0;
for(i=0; i<myArray.length; i++){
var number = parseInt(myArray[i], 10);
total += number;
}
Use parseInt or parseFloat (for floating point)
var total = 0;
for (i=0; i<10; i++)
total+=parseInt(myArray[i]);

Categories

Resources