Summing of numbers in jquery returning NAN - javascript

I'm trying to sum values from an input array but the sum it keeps returning NAN
var sum = 0 //i have also tried parse(0,10);
$(qty_name).each(function(){
var aValue = $(this).val(); //i have tried parseInt($(this).val(), 10)
sum += aValue; //i have tried sum = parseInt(sum) + parseInt(aValue)
});
alert(sum);
i keep getting NaN. I'm coming from a php background so i've never had to deal with type casting. Please what am i missing?

That is because your other qty_name do not have perfect integer value. which results to NAN for such values. You need to parse the values to int(or float) for doing any mathematical calucations:
var sum = 0;
$(qty_name).each(function(){
sum += parseInt($(this).val()) || 0;
});
alert(sum);

Do like this:
var sum = 0;
$(qty_name).each(function(){
sum += +($(this).value()); //+ converts to a number
});
alert(sum);
You were doing wrong with var aValue += $(this).val() where you're defining the variable you should not use += operator. You should have done like this:
var sum = 0 //i have also tried parse(0,10);
$(qty_name).each(function(){
var aValue = $(this).val(); //removed + sign before = sign
sum += aValue; //i have tried sum = parseInt(sum) + parseInt(aValue)
});
alert(sum);

As far as i understand from your question, you try to avoid adding NaN, use the jQuery built-in method .isNumeric() for that like (and of course += on undefined doesn't end well):
var sum = 0;
$(qty_name).each(function(){
var aValue = parseInt($(this).val(), 10);
if(!$.isNumeric(aValue)) return;
sum += aValue;
});
alert(sum);

Try using isNaN and parseInt as shown :
var sum = 0;
$(qty_name).each(function(){
sum += (isNaN($(this).val()) ? 0 : parseInt($(this).val(),10));
});
alert(sum)

You need to use parseInt or parseFloat, but here you are using var aValue += $(this).val(); and aValue is not initialised. Directly add value to sum
var sum = 0;
$(qty_name).each(function(){
sum += parseInt($(this).val(), 10)||0;
});
alert(sum);

Related

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 can I do an addition of all price elements from a json array in javascript

I have the following JSON array:
fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
How can I calculate all the "price" values together? The result should be 8.
I have so far the following but problems accessing the price items:
function count(fruits) {
var sum = 0;
for (var i = 0; i < fruits.length; i++) {
sum = sum + fruits[i][price];
}
return sum;
}
console.log(count(fruits)
Thank you!
You need to access them like:
fruits[i].price
and then convert them to numbers before adding them:
parseInt(fruits[i].price, 10);
Final code:
fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
var total = 0;
for(var i=0; i<fruits.length; i++){
total += parseInt(fruits[i].price, 10);
}
alert(total); //8
See the DEMO here
Two things:
The line
sum = sum + fruits[i][price];
should be
sum = sum + fruits[i].price;
or even
sum += fruits[i].price;
Your code was trying to use a variable called price, not the price property of the fruit entry.
Your prices are strings, so we want to make sure they're converted to numbers when summing them up. You have lots of options there: Apply a unary + to them, pass them into Number(), or use parseInt(..., 10). Below I'll go with a unary +, but there are pluses (no pun!) and minuses to each.
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
for (var i = 0; i < fruits.length; i++) {
sum += +fruits[i].price; // <=== change is here
}
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
With ES5's array additions (which can be shimmed on older browsers), you can do this with either forEach or reduce:
forEach:
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
fruits.forEach(function(fruit) {
sum += +fruit.price;
});
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
reduce:
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
sum = fruits.reduce(function(prev, fruit) {
return prev + +fruit.price;
}, 0);
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
Your code has 2 errors:
To access the price property
fruits[i][price]
should be
fruits[i]['price'] or fruits[i].price
The price property is of type string. So the '+' operator will concatenate the price strings. To add them together you need to change their type to number by doing
parseInt(fruits[i]['price'], 10) or +fruits[i]['price']
If the price property doesn't contain a valid number the result will be NaN (not a number). You could avoid that by using the or operator.
+fruits[i]['price'] || 0
Using the ES5 Array extensions supported by all modern browsers you could write
fruits.reduce(function(m,v) { return m + (+v.price);}, 0);
With ES6 in future browsers this could be reduced to
fruits.reduce((m,v) => m + (+v.price), 0);
You have some errors in your code.
The first one is here: sum = sum + fruits[i][price];
you are trying to use a variable called price, not the property price of the object. You can access to the property using fruits[i]["price"] or fruits[i].price.
To obtain a number, when you are doing the sum, you need to convert the strings in numbers, to do that you can use parseInt(fruits[i]["price"]);. Last error in the last line you forgot the parenthesis and semicolon.
JSFiddle
your function is OK, just add parseInt for it to convert to type int, and has a incorrect syntax in fruits[i][price].
You've two option:
fruits[i]["price"]
OR
fruits[i].price
In my opinion, I would add a small logic code to check if it's a number or not. and return 0 if input data is undefined or null.
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(data) {
var sum = 0;
if(data === void 0 ) return 0; // no array input
data.forEach(function(fruit) {
console.log(fruit);
sum += parseInt(fruit.price || 0 ); // if price is undefined, null or NaN, return 0
})
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
You should try this simple code snippet.
You don't need jQuery to do this operation. Simple JS would do.
var sum = 0;
for(var item in fruits){
sum += ~~(fruits[item].price)
}
console.log(sum)
Cheers!

javascript storing array values

Im trying to get the total combined value of a set of numbers.
Im getting the numbers as the text in an element tag storing them in an array then adding them all together. My problem is that its not inserting the numbers into the array as pairs.. it adding them as single integers .what am doing wrong.
check the jsfiddle too see example
http://jsfiddle.net/Wd78j/
var z = $('.impressions').text();
var x = [];
for(var i = 0; i < z.length; i++){
x.push(parseInt(z[i]));
}
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
When you get text, it's taking all the numbers and concatenating them into a string. The below takes each element one at a time and pushes it.
var x = [];
$('.impressions').each( function( ) {
var z = $(this).text();
x.push(parseInt(z, 10));
})
Of course, you could build the sum up inside that each function, but I did it like this to more closely mirror your code.
text() returns the concatenated text of all of your impressions elements, of which you're adding together each character.
You want to loop through each impressions element, and keep a running sum going. Something like this should work
var sum = 0;
$('.impressions').each(function(){
sum = sum + (+$(this).text());
});
Updated Fiddle
Or to keep your original structure (don't forget the radix parameter to parseInt):
var z = $('.impressions');
var x = [];
z.each(function(){
x.push(parseInt($(this).text(), 10));
});
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
Updated fiddle
You are iterating over a string, you could just use $.map to build the array instead, if you need it, otherwise just iterate and sum up the values :
var x = $.map($('.impressions'), function(el,i) {return parseInt($(el).text(), 10);}),
total = 0,
n = x.length;
while(n--) total += x[n] || 0;
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
FIDDLE

Add all values with input name="TotalInline[]"

How to add values from all input with name name="TotalInline[]"?
The following does not seams to work:
var total = 0;
$.each('input[name="TotalInline[]"];,function() {
total += this;
});
This should work :
var total = 0;
$('input[name="TotalInline"]').each(function() {
// assuming you have ints in your inputs, use parseFloat if those are floats
total += parseInt(this.value, 10);
});
var total = 0;
$.each($('input[name="TotalInline[]"]'), function() {
total += parseInt(this.value, 10);
});
You have some serious syntax errors, try this:
var total = 0;
$('input[name="TotalInline[]"]').each(function () {
total += parseInt(this.value, 10);
});
Try like this...
var total = 0;
$('input[name="TotalInline[]"]').each(function() {
total += parseInt($(this).val(),10);
});
var total = 0;
$('input[name="TotalInline[]"]').each(function() {
total += +this.value.replace(/[^\d.]/g, '');
});
Uses a quick regex to filter out only the numbers (and decimal point).
Uses a + prefix to convert to a number.

Decimal places in JS

I have two form inputs which display the calculated invoice sub-total and total of a form.
The problem I'm having is it's not displaying 2 decimal places.
Subtotal function:
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".row-total-input").each(function(){
var valString = $(this).val() || 0;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(prodSubTotal);
};
Total function
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var productTax = $("#product-tax").val() || 0;
var orderTotal = parseInt(productSubtotal) + parseInt(productTax);
var orderTotalNice = "$" + orderTotal;
$("#order-total").val(orderTotalNice);
};
How do I go about displaying two decimal places?
change $("#product-subtotal").val(prodSubTotal);
to $("#product-subtotal").val(addDecimals(prodSubTotal));
and change $("#product-subtotal").val(prodSubTotal);
to $("#product-subtotal").val(addDecimals(prodSubTotal));
function addDecimals(a){
a += "";
var i=a.indexOf('.');
if(i<0){
return a + ".00";
}
var j = a.substring(i);
console.log(j);
if(j.length<3){
for(var k=j.length;k<3;k++)
a+='0';
return a;
}
if(j.length>3){
return a.substring(0, i)+j.substring(0,3);
}
}
You may want to look here:
http://www.mredkj.com/javascript/nfbasic2.html
Basically you can use toFixed(2), but then you get some rounding.
Or, if rounding is bad you can do parseInt(productTax * 100) / 100.
If you are working with real numbers it would be better to use parseFloat instead of parseInt. To format the number you could use the toFixed function:
$("#product-subtotal").val(prodSubTotal.toFixed(2));

Categories

Resources