Why do i see the NaN for total price? - javascript

I ahve already the script almost finished, but the total price is not showing up i still see NaN as results for the total price, why is this? and how can i quick fix this?
http://jsfiddle.net/9zPTA/135/
This is my jquery code:
$("input").on("keyup", function () {
var $input = $(this);
var howMany = parseInt($input.val());
var unitAmount = parseInt($input.parent().prev().text().replace("€", ""));
var total = howMany ? howMany * unitAmount : 0;
$input.parent().next().text("€ " + total);
var total = 0;
$("tbody tr td:last-child").each(function() {
total += parseInt($(this).text().replace("€","") || 0);
});
$("#total").html("€ " + total);
});

Your selector, and the brackets typo, are the problems. The brackets typo on parseInt
total += parseInt($(this).text().replace("€","") || 0);
parses $(this).text().replace("€","") || 0 which is not what you want.
Also, you were erroneously including the final row's <td> (which holds the current total!) in your total calculation. This resulted in the increasing total you were experiencing.
Change
$("tbody tr td:last-child")
to
$(".tdPrice.tdDarker")
Try this:
var total = 0;
$(".tdPrice.tdDarker").each(function() {
var val = parseInt($(this).text().replace("€",""));
total += isNaN(val) ? 0 : val;
});
$("#total").html("€ " + total);
Aside: Sometimes you have entries with no money value, like
<td class="tdPrice"> <div id="u_KiloFineSilver"></div></td>
versus
<td class="tdPrice">€ 10 <div id="u_barFineSilver"></div></td>
which will cause an NaN in the subtotal, but with my solution above the final total will not be NaN.
How can I hide the "0" value if someone enters, for example, 3 and then hits backspace?
Change
$input.parent().next().text("€ " + total);
to
$input.parent().next().text("€ " + (total > 0 ? total : ""));
Demo: http://jsfiddle.net/9ka2u5px/1/

Change total += parseInt($(this).text().replace("€","") || 0); to total += parseInt($(this).text().replace("€","") | 0);

Related

Why are these numbers not summing in a for loop using javascript?

I'm iterating over a range, extracting 2 texts (to be converted into numbers) and summing them to put the total back into the stirng later.
However, although I see the numbers logged ok, the sums give me NaN as the results.
Here's the code piece:
var totalPriceToPay = 0;
var totalCODAmount = 0;
if (ss.getActiveSheet().getName() == sheet.getName() && row > 1) {
for (var a = 0; a < dataRng.length; a++) {
if (dataRng[a][1] == true && dataRng[a][0] == 'SHIPPED' && dataRng[a][40] != 'Yes') {
//Isolate the Price to Pay Amounts to be summed and put the total back into the string.
const str = dataRng[a][35].toString();
const priceToPay = str.split(",").slice(8, 9)[0] //Extracts 8th element
totalPriceToPay += Number(priceToPay) //Converts it into a nº and sums to the total
const codAmount = str.split(',').slice(9, 10)[0] //Extracts the 9th element
totalCODAmount += Number(codAmount) //Converts it into a nº and sums to the total
Logger.log('Type Price To Pay: ' + str.split(",").slice(8, 9)[0]);
Logger.log('Type codAmount: ' + str.split(",").slice(9, 10)[0]);
Logger.log('Total Price to Pay: ' + totalPriceToPay);
Logger.log('Total COD: ' + totalCODAmount);
Here are the logs:
Thanks.
The numbers have a $ before it. You need to remove it. Use String.slice:
const priceToPay = Number(str.split(",")[8].slice(1));
The Number() constructor will give NaN when the value cannot be converted to a number. When you add NaN to a number, you get NaN. To avoid the issue, use this pattern:
totalPriceToPay += Number(priceToPay) || 0;
totalCODAmount += Number(codAmount) || 0;

Calculating sum of fractions in a loop

Implement a function fractionSum(n) that calculates and returns the sum of the following sequence:
1/n + 1/(n−1) + 1/(n−2) + ⋅⋅⋅ + 1/2 + 1
For example, fractionSum(5) calculates the following sum: 1/5+1/4+1/3+1/2+1
And then returns 2.283333333333333
I haven't even started writing function just yet since I'm still stuck at trying to figure out the right loop expression. This is what I've done so far:
var sum =0;
var fraction = 1;
var number = parseInt(prompt("Enter an integer: ", "5"));
for ( var counter = 0; counter <= number; counter++) {
fraction /= (number - counter); // do I need to declare parseFloat here for decimal# ?
sum += fraction;
}
document.write("The total value is " + sum);
The number doesn't match up at all from the example. I'm not sure what the problem is here.
I'm pretty confused right now. I know this is basic problem but I has tried multiple codes and it still didn't come out right.
Thank you so much
You're reusing the fraction from the previous iteration and dividing it by the next value. You need a new fraction instead:
fraction = 1 / (number - counter);
Also, you need the strict counter < number condition in the loop to avoid division by zero.
In the loop, counter must be less than number else at the end there will be divison by 0, the result will be infinity. Try this
let sum = 0;
let i = 0;
let num = parseInt(prompt("Enter an integer: ", "5"));
for(i; i < num; i++ ){
frac = 1 / ( num - i);
sum+= frac;
}
I figured it out. This is what I got:
<script>
function fractionSum(number) {
var sum =0;
for (var counter= 0 ; counter < number; counter++) {
sum += 1/(number - counter);
}
return sum;
}
var number = parseInt(prompt("Enter the value of n: ", "5"));
sum = fractionSum(number);
document.write("The fraction sum of order " + number + " is " + sum);
</script>
Thank you guys, it was very helpful

Summing of numbers in jquery returning NAN

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);

Compound assignment in Javascript resulting in NaN

I'm trying to get compound assignment working inside a loop in Javascript but it's throwing NaN at me and I don't know why as I'm still fairly new to Javascript. I am essentially trying to translate this into a jQuery-Validation custom method: https://github.com/pfwd/NHSNumber-Validation/blob/master/PHP/NHSValidation.class.php
Here's what I have so far
// Taken from https://github.com/pfwd/NHSNumber-Validation
var multipliers = {1:10, 2:9, 3:8, 4:7, 5:6, 6:5, 7:4, 8:3, 9:2};
var currentSum, currentNumber, currentMultiplier = 0;
//Get submitted NHS Number and remove whitespace
var givenNumber = value.replace(/\s+/g, '');
// Get length
var numberLength = givenNumber.length;
console.debug(givenNumber);
console.debug(numberLength);
// Number must be 10 digits in length
if (numberLength !== 10) {
return false;
}
// Check number
var checkNumber = value.substring(9);
console.debug(checkNumber);
// Loop over each number in the string and calculate the current sum
for (var i = 0; i <= 8; i++) {
var minus = i-1;
var plus = i+1;
currentNumber = value.charAt(i);
currentMultiplier = multipliers[plus];
currentSum += (currentNumber * currentMultiplier);
console.debug("i is " + i + " & current Num: " + currentNumber + " plus current multi: " + currentMultiplier + " plus " + currentSum);
}
var remainder = currentSum % 11;
var total = 11 - remainder;
console.debug(currentSum);
I don't know if the minus and plus vars are necessary but they're something I tried while trying to fix the NaN issue. A typical console debug line looks like this:
i is 0 & current Num: 1 plus current multi: 10 plus NaN
I've also tried this with the same NaN result:
currentSum = currentSum + (currentNumber * currentMultiplier);
var currentSum, currentNumber, currentMultiplier = 0;
is incorrect, and only initalizes currentMultiplier.
It should be
var currentSum, currentNumber, currentMultiplier;
currentSum = currentNumber = currentMultiplier = 0;
demo : http://jsfiddle.net/46dD5/

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.

Categories

Resources