get sum of float values in table cells - javascript

I have a table of fines people owe:
<tr><td class='fines'>104.20</td></tr>
<tr><td class='fines'>26.40</td></tr>
<tr><td class='fines'>99.14</td></tr>
I am trying to get the sum of the cells:
var sumFines = "";
$.each($('.fines'),function(){
alert($(this).html());
sumFines += parseFloat($(this).html());
})
alert(sumFines);
The result of each alert in each loop is the number in the cell. The result of the final alert is "NaN", Why?

When you sum
"" + 120
the result return a string, you must sum number, so change
var sumFines = "";
to
var sumFines = 0;

I need to set initial value of sumFines to 0.

var sumFines = 0;
$.each($('.fines'),function(){
alert($(this).html());
sumFines += parseFloat($(this).html());
})
alert(sumFines);
var sumFines = ""; makes sumFines a string and that's the reason you get NaN because you are doin arithmatic operations with a string and float which can't be cast together.

If you want to keep the .each approach, just change your initial value to 0.
var subtotal = 0;
$('.fines').each(function() {
subtotal += !isNaN(+$(this).html()) && +$(this).html();
});
alert(subtotal);
The line:
!isNaN(+$(this).html()) && +$(this).html();
asserts that you are effectively adding a number, else nothing.
fiddle
http://jsfiddle.net/hem7q4fn/2/

Nan reduce whole expression to NaN
try:
var sumFines = 0;
$('.fines').each(function () {
var num = parseFloat($(this).txt());
sumFines += isNaN(num) ? 0 : num;
});
alert(sumFines);

Related

Can not adding up numbers in a column with angular

Im trying to get the sum of a column ("price") with angular with this code, but only have the value.
Example:
Price: 5,7,8,9
Total Price:05789
$scope.totalPrice = function(){
var total = 0;
for(count=0;count<$scope.names.length;count++){
var product = $scope.names[count];
total += (product.price);
}
return total;
};
It looks like the product.price is str, so each time you use +=, you are concatenating the string.
Try using parseFloat or parseInt
$scope.totalPrice = function(){
var total = 0;
for(count=0;count<$scope.names.length;count++){
var product = $scope.names[count];
total += parseFloat(product.price);
}
return total;
};
EDIT 1:: Double checking it, you declare var total = 0 and that is a Int, the += between a Int and a str should give a Int... weird stuff...
EDIT 2: Well, triple checking it... the first thing I said was ok :D 0 + "0" gives "00"

Calculation form, behind the comma

This calculation script works almost, but it doesn't do anything with a value with a number behind the comma. Can anyone help me?
var selects = $('select');
var inputs = $('input');
selects.change(calculate);
inputs.keyup(calculate);
function calculate()
{
var runningTotal = 0;
selects.each(function(i)
{
var val = parseInt($(this).val());
var qty = inputs.eq(i).val();
runningTotal += (val*qty);
});
$('#grandtotal').val(runningTotal);
}
If you're trying to convert a string to a number with a decimal point, don't use parseInt(), but parseFloat() instead.
jsfiddle: http://jsfiddle.net/Grimbode/mjs32/1/
alert(parseInt('10.10'));
alert(parseFloat('10,10'));
alert(parseFloat('10.10'));
You need to convert you commas to '.'s apparantely for the parseFloat() to work.
parseFloat(('10,10').replace(",", "."));
selects.each(function(i)
{
var val = parseInt($(this).val());
if (val.indexOf('"') != -1) {
val = val.replace(/"/g, '');
}
var qty = inputs.eq(i).val();
runningTotal += (val*qty);
});

Trying to add up an array, but result returns NaN

So I have a string called hoursString that looks like
4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|
I split the string into an array and what I am trying to do is add up all the numbers and return it to the html page in the div "test".
JAVASCRIPT:
var hours=hoursString.split("|");
var total=0;
for (var i=0;i<hours.length;i++)
{
total += hours[i];
}
document.getElementById("test").innerHTML=total;
The result is NaN. Can someone tell me what I am doing wrong?
Thanks!
4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|
remove the last |, split will otherwise add an empty string at the end of the array which will give NaN and NaN + number evaluates to NaN
edit: and yes, parseFloat is necessary too, otherwise the result will be a string instead of NaN
var hoursString = "4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|",
hours = hoursString.split("|"),
total = 0;
for (var i = 0; i < hours.length; i++) {
total += parseFloat(hours[i]) || 0; // see explanation
}
document.getElementById("test").innerHTML = total;
Why the || 0? Because it checks if the string is "", if so the || operand will return the second value, in this case 0.
This will output 25.740000000000002. See this answer on the cause of the "wrong" result, and here is a working fiddle.
Your issue is that each element in hours is still a string value even though it is written as a number. The easiest way to fix this would be to use javascripts parseFloat() function.
Example:
var hours=hoursString.split("|");
var total=0;
for (var i=0;i<hours.length;i++)
{
total += parseFloat(hours[i]);
}
document.getElementById("test").innerHTML=total;
EDIT: Changed from parseInt to parseFloat
var hoursString = "4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|"
var hours=hoursString.split("|");
var total=0;
var idx = 0;
for(idx in hours) {
total += +hours[idx];
}
alert(total);
FIDDLE

issue to sum fields

This is a basic html/javascript code, but I am having issues getting the sum of all fields.
(The are 50 fields in the original project, but now I just leave 5)
If the field is blank, it just has to ignore it, and add only those with filled fields.
HTML code:
value1:<input type="text" id="total_1" ><br>
value2:<input type="text" id="total_2" ><br>
value3:<input type="text" id="total_3" ><br>
value4:<input type="text" id="total_4" ><br>
value5:<input type="text" id="total_5" ><br>
total:<input type="text" id="totalresult" >
<button type="button" onclick="getTotal(); return false;">Get total</button>
Javascript:
function getTotal() {
var sum;
for (i = 1; i <=5 ; i++) {
var total = document.getElementById('total_' + i.toString()).value;
if (total != '') {
sum = parseFloat(total) + sum;
document.getElementById('totalresult').value = sum;
}
}
}
I don't know why my code is isn't working.
Here is my Fiddle
The first time your code runs, sum will be undefined.
Initialize
var sum = 0;
Also to make it work in the fiddle, you need to change
the onLoad on the left top to 'No wrap - in '
You need to do two things. 1, initialize sum to zero. 2, check the input values for not being a number.
function getTotal() {
var sum = 0;
for (i = 1; i <= 5; i++) {
var total = document.getElementById('total_' + i).value;
if (!isNaN(parseFloat(total))) sum = parseFloat(total) + sum;
document.getElementById('totalresult').value = sum;
}
}
jsFiddle example
I don't know why your fiddle can't figure out to make getTotal a global. But your main problem is that sum is undefined as start. This will result in NaN (Not a Number) :
var sum;
sum = 1 + sum; // NaN
....
sum = 1 + undefined; // NaN
sum = 1 + NaN; // NaN
Demo at jsbin.com
You should set sum equal zero at first:
var sum = 0;
for ( ... ) { ...
Working demo as adrianp pointed out: It would probably be more clear if you uploaded the working code to jsbin.
You haven't defined sum variable so javascript takes that as NaN, which means Not a Number. You need to initilaize it to set it right.
function getTotal() {
var sum = 0;
for (i = 1; i <=5 ; i++) {
var total = document.getElementById('total_' + i.toString()).value;
if(isNaN(total) || total.indexOf(' ') == 1) {
alert("Please type a number");
document.getElementById("totalresult").value = "I cant sum alphanumerics";
return false;
}
if (total != '') {
sum = parseFloat(total) + sum;
document.getElementById('totalresult').value = sum;
}
}
}
FIDDLE
Use IsNumeric function to check if the input field has a valid number. See: Validate decimal numbers in JavaScript - IsNumeric()
Here is my suggestion to improve the code inside your for loop:
var elementValue = document.getElementById('total_' + i).value
IsNumeric(elementValue) ? elementValue : elementValue = 0;

JQuery addition from .text()

I have a variable count set to zero.
var count = 0;
Then I run through a .each() loop to update the count. The .text() parameter will always return a text number.
$(this).find('.outersubtopic').each(function(idx)
{
var temp = $(this).text();
count += temp;
});
alert(count);
When I hit the alert, it always reads 0008 instead of just 8.
How do I turn the .text() into a real number?
$(this).find('.outersubtopic').each(function(idx)
{
var temp = $(this).text();
count += window.parseInt(temp);
});
alert(count);
window.parseInt() should do it for you.
you have to convert it to an Number
$(this).find('.outersubtopic').each(function(idx)
{
var temp = $(this).text();
count += Number(temp);
});
alert(count);
try using parseInt
$(this).find('.outersubtopic').each(function(idx)
{
var temp = $(this).text();
count += temp;
});
alert(parseInt(count));
count += 1 * temp; // quick way to change string to number

Categories