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())
Related
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>
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]);
}
}
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>
I found this in another post:
<script language='javascript'>
function AddInputs()
{
var total = 0;
var coll = document.getElementsByClassName('add')
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseInt(ele.value);
}
var Display = document.getElementById('Display');
Display.innerHTML = total;
}
</script>
It works, but 1.50, 1.50, and 1.50 = 3 which isn't accurate. I'm new to JS (only know PHP), but I looked into it and figure it has something to do with parseInt since 1.50 isn't a whole number. Is there something I can replace parseInt with to calculate it so that the three 1.50 actually equals 4.50?
Try to use parseFloat() instead of parseInt()
Also use <script type="text/javascript"> instead of <script language="javascript"> that will be more standard and correct
parseInt will convert any decimal to an integer so parseInt(1.5) becomes 1. That is why parseInt(1.5) + parseInt(1.5) + parseInt(1.5) = 3. If you want it to equal 4.5 then just replace parseInt with parseFloat:
function AddInputs()
{
var total = 0;
var coll = document.getElementsByClassName('add')
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseFloat(ele.value);
}
var Display = document.getElementById('Display');
Display.innerHTML = total;
}
When you call parseInt on 1.50 you're getting the integer part of that value (1 in this case). Just replace parseInt with parseFloat and you'll get the value you expect.
Beside parseFloat you can also use Number to convert a string to a numeric value.
document.querySelector('#add').addEventListener('click', addNumber)
var total = 0;
function addNumber(e) {
total += Number(document.querySelector('#plus').value);
document.querySelector('#result').innerHTML = 'total: '+total.toFixed(2);
}
<input id="plus" type="number" placeholder="type a number"/>
<button id="add">add to total</button>
<div id="result"></div>
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);