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"
Related
I have a <p id="rabbits">1 2 9 4</p>' And i'm trying to calculate all the 1,2,9,4
However, I'm stuck at this part:
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(/(\s+)/);
for (i in rabbits_array) {
console.log(i) // prints 1,2,9,4
}
How do add all of these numbers together (which is 16 if you count manually) in javascript?
Can map array to number and use reduce
var rabbits = $('#rabbits').text()
var total = rabbits.split(" ").map(Number).reduce((a,c) => a + c)
console.log(total)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="rabbits">1 2 9 4</p>
There are a variety of ways to do this.
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(/(\s+)/);
var total = 0;
rabbits_array.forEach(function(element) {
total += element * 1;
});
console.log(total);
You could use a standard for loop:
for (var i = 0; i < rabbits_array.length;i++) {
total += rabbits_array[i] * 1;
}
You could replace the "multiply by 1" (which would have to validate beforehand that it's actually a number and not a letter), with parseInt or parseFloat. Using these methods can do some of this validation for you, but may also give you odd results.
total += parseFloat(rabbits_array[i]);
https://www.w3schools.com/jsref/jsref_parseint.asp
There are other ways to do this as well, but these are just a few examples to get you going. I'd suggest Googling "javascript loops" to read more about this kind of thing.
Try this:
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(" ");
var total = 0;
for (var i = 0; i < rabbits_array.length; i++) {
total = total + parseInt(rabbits_array[i]);
}
console.log(total)
You need to convert the string version of the number (from your split function) to an actual number before adding them together
I have an input field where users can enter decimal numbers by using a Dot or a comma ( Example: 79,99 or 79.99 ) . When users enter the number with a comma I replace it with a dot ( this number is then sent to a remote server for verification) . Now I would like to display the number after the user enters it in the footer using toFixed(2) function to display only the first two decimal numbers. I cant get it to work , because after converting it back to a number using ParseFloat the 2 decimals after the comma disappear.
Example:
User enter in the input field : 79,99 which is then set into the variable totalAmount:
$('#amount-1').keyup(function() {
getRefundAmount(1); // This function calls the calcTotalAmount function
})
function calcTotalAmount() {
console.log('calcTotalAmount');
var totalAmount = 0;
var totalRefund = 0;
var rowAmount = 0;
var rowRefund = 0;
for(var i = 1; i < 4; i++ ) {
rowAmount = parseFloat($('#amount-' + i).val());
rowRefund = parseFloat($('#result-' + i).text());
if(!isNaN(rowAmount)) {
totalAmount += rowAmount;
totalRefund += rowRefund;
}
}
var toPay = totalAmount-totalRefund;
totalAmount = totalAmount.toString().replace(/\,/g, '.');
totalAmount = parseFloat(totalAmount).toFixed(2);
$('#footer-refund').text(totalRefund)
$('#footer-total').text(totalAmount)
if (totalAmount == '') {
$('#footer-total').text("0.00");
}
}
The Result displayed in the footer is : 79.00 instead of 79.99
I tried your code in jsfiddle and got an error on the ".toFixed(2)"
After changing it a bit i could prevent the error.:
$(function() {
var totalAmount = '79,99';
totalAmount = parseFloat( totalAmount.toString().replace(/\,/g, '.'));
totalAmount = totalAmount.toFixed(2);
$('#footer-refund').text(totalAmount)
});
https://jsfiddle.net/jkrielaars/2gb59xss/1/
It seems like the code you've given works just fine but there are some fixes you could apply :
totalAmount = ("" + totalAmount).replace(/\,/g,'.');
totalAmount = parseFloat(totalAmount);
//use toFixed only if you don't restrict input to 2 decimals, but I'd recommend restricting input otherwise you'll encounter rounding issues
Btw, you do $('#footer-refund').text(totalRefund.toFixed(2)), shouldn't it be $("#footer-refund").text(totalAmount) (not sure why you use toFixed here too) ?
Thanks for all the help :
solution is as follows : I have to check it in the for loop already and replace it there.
for(var i = 1; i < 4; i++ ) {
if(!$('#amount-' + i).val()){continue;}else{
rowAmount = parseFloat($('#amount-' + i).val().toString().replace(/\,/g,'.'));
rowRefund = parseFloat($('#result-' + i).text());
if(!isNaN(rowAmount)) {
totalAmount += rowAmount;
totalRefund += rowRefund;
}
}
}
I have an object and need to sum/average of each dynamic span. Can't seem to convert those to numbers though. Please Help.
Console Log
Code Sample
Expand/Collapse Created : 1/3/2017 <span>(10)</span>
Expand/Collapse Created : 1/4/2017 <span>(38)</span>
Expand/Collapse Created : 1/5/2017 <span>(13)</span>
Expand/Collapse Created : 1/6/2017 <span>(35)</span>
Expand/Collapse Created : 1/9/2017 <span>(46)</span>
Expand/Collapse Created : 1/10/2017 <span>(17)</span>
Expand/Collapse Created : 1/11/2017 <span>(27)</span>
var arr = [];
$(".ms-gb span").each(function(index, elem){
arr.push($(this).text());
});
$("#result").text(arr.join("+")); // (10)+(38)+(13)+(35)+(46)+(17)+(27)
var allNumbers = document.getElementById('result').innerText; // (10)+(38)+(13)+(35)+(46)+(17)+(27)
allNumbers = allNumbers.replace(/["'()]/g,""); // 10+38+13+35+46+17+28
var newString = allNumbers.split("+"); // Object - ["10", "38", "13", "35", "46", "17", "27"]
well you're pretty close. i'd recommend using the reduce function
var sum = allNumbers.reduce(function(a,b){ return +a + +b; }, 0)
the plus signs in front of a and b might look weird, but its a quick way to coerce a string into a number in javascript
You can strip out non-numeric characters, parse each number, and then perform the addition within the loop.
// variables
var sum = 0;
var average = 0;
var numOfSpan = $('span').length;
// each span loop
$('span').each(function(key, val){
// add the value of the span to the sum var
sum+= parseInt($(this).text().replace(/\D/g,''));
// on the last itteration ...
if(key == (numOfSpan - 1)) {
// calulate average
average = sum / numOfSpan;
// log sum and average
console.log('sum = ' + sum);
console.log('average = ' + average);
}
});
<span>(10)</span>
<span>(38)</span>
<span>(13)</span>
<span>(35)</span>
<span>(46)</span>
<span>(17)</span>
<span>(27)</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You have to iterate your array and then change every string to number. After that you can add every elements to itself.
var a = 0;
for(var i=0;i<newString.length;i++) {
a += parseInt(newString[i]);}
And then a will be the sum
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);
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