My function keeps giving NaN - javascript

I have made a function but it keeps returning NaN. I can't figure it out why it does this.
function voeruit(){
var invoer1 = 2000;
var invoer2 = 11000;
var invoer3 = 5;
var datum = new Date();
var jaar = datum.getFullYear();
berekenen(invoer1, invoer2, invoer3, jaar);
}
function berekenen(invoer1, invoer2, invoer3, jaar)
{
var leeftijd = jaar - invoer1;
var daling1 = invoer3 / 100;
var daling = 1 - daling;
var totdaling = Math.pow(daling, leeftijd);
var waarde = invoer2 * totdaling;
var uitkomst = waarde;
window.alert(uitkomst);
}
it's a summary where, i think is the problem, so there might be a syntax error.
It's an other language than english, because i'm dutch

Your code has a bug here:
var daling = 1 - daling;
Which should be:
var daling = 1 - daling1;

Looks like you have a typo
var daling1 = invoer3 / 100;
var daling = 1 - daling; //<-- daling1?
Presumably that should be
var daling1 = invoer3 / 100;
var daling = 1 - daling1;
Otherwise you're setting daling to 1 - undefined. Which is indeed not a number.

To able to return something from function you should use
return someValue;
But in your code i could not find something like this. How can you expect function return the value if you dont write return statement?

You are using var daling = 1 - daling; and daling not defined yet, may be you should use daling1
And also I want to suggest to not use variable names which like each other they are always confusing.

Related

Using JSON powered variables to perform JS math

I am trying to perform some JS math to add a total value, based upon a series of variables which obtain their values from a JSON object. However when I run the script in the browser, the console log shows me almost half of the sum done and half just chained together as a string.
If I paste the following into the console:
var sparksOfferCount = 10;
var sparksAddedOffers = 3;
var sparksUNaddedOffers = (sparksOfferCount - sparksAddedOffers); // offers that haven't been added yet
var sparksAllRewards = 0;
var sparkstotalStreakOffers = 0;
var derivedSparksTotalOffers = (sparksUNaddedOffers + sparksAllRewards + sparkstotalStreakOffers);
console.log('derived total of new offers', derivedSparksTotalOffers);
It will return 7. However, above I have replaced references to the JSON object with actual integers. When I run my code like this where it takes it's values dynamically from the JSON call, it returns '70' in the console. Bizarre, because it means that it is able to subtract 3 from 10 and then add one 0 for sparksAllRewards, but it doesn't show another 0 for sparkstotalStreakOffers.
var sparksSSO = JSON.parse(sessionStorage.getItem('sparksSSO')) || {};
// global variables for use with session storage
var sparksOfferCount = (sparksSSO.totalOffers >= 0) ? sparksSSO.totalOffers : "" ;
var sparksAllOffers = (sparksSSO.allOffers);
var sparksAddedOffers = (sparksSSO.totalAddedOffers);
var sparksUNaddedOffers = (sparksOfferCount - sparksAddedOffers); // offers that haven't been added yet
var sparksAllRewards = (sparksSSO.allRewards);
var sparkstotalStreakOffers = (sparksSSO.totalStreakOffers);
var derivedSparksTotalOffers = (sparksUNaddedOffers + sparksAllRewards + sparkstotalStreakOffers);
console.log('derived total of new offers from session storage', derivedSparksTotalOffers);
I'm rather baffled. Any ideas?
EDIT:
Here is the working script, as per the guidance of Arthur Borba
var sparksOfferCount = (sparksSSO.totalOffers >= 0) ? sparksSSO.totalOffers : 0 ;
var sparksAllOffers = Number(sparksSSO.allOffers);
var sparksAddedOffers = Number(sparksSSO.totalAddedOffers);
var sparksUNaddedOffers = Number(sparksOfferCount - sparksAddedOffers); // offers that haven't been added yet
var sparksAllRewards = Number(sparksSSO.allRewards);
var sparkstotalStreakOffers = Number(sparksSSO.totalStreakOffers);
var derivedSparksTotalOffers = Number(sparksUNaddedOffers + sparksAllRewards + sparkstotalStreakOffers);
console.log('derived total of new offers from session storage', derivedSparksTotalOffers);
Try initializing your counter
var sparksOfferCount = (sparksSSO.totalOffers >= 0) ? sparksSSO.totalOffers : "" ;
with a zero (not an empty string), like this:
var sparksOfferCount = (sparksSSO.totalOffers >= 0) ? sparksSSO.totalOffers : 0 ;
And also check this Number so you ensure you are working with numbers and not strings:
var sparksAllOffers = Number(sparksSSO.allOffers); // do it for every variable
If that's not quite what you want, please provide some example of your JSON data.

JS Percentage Calculation in a single line?

I am calculating the percentage increase between two numbers , based on the formula
newnumber - oldnumber
----------------------- * 100
oldnumber
var oldNumber = 33, newNumber = 40;
var percent = newNumber - oldNumber;
var percent2 = percent/oldNumber;
var PercenIncr = Math.ceil(percent2*100).toFixed(2);
alert(PercenIncr)
http://jsfiddle.net/416jkaz7/2/
Can i do all this in a single line ?
Try this
var oldNumber = 33, newNumber = 40;
var PercenIncr = Math.ceil(((newNumber - oldNumber)/oldNumber)*100).toFixed(2);
alert(PercenIncr)
Building on the (perfectly correct) answer from #ellipsis, you could also create a function to do this even more succinctly.
const percentIncrease = (oldNumber, newNumber) => Math.ceil(((newNumber - oldNumber)/oldNumber)*100).toFixed(2);
alert(percentIncrease(33,40)); // => 22.00
alert(percentIncrease(55,72)); // => 31.00
EDIT:
As mentioned by the comment #svenQ, arrow functions (=>) are not supported in IE11 or below. You would therefore need to do something like this for older browsers:
var percentIncrease = function(oldNumber, newNumber) {
return Math.ceil(((newNumber - oldNumber)/oldNumber)*100).toFixed(2)
}
You can also use polyfills or services like Babel compile your JavaScript for older browsers
try this instead,
this code will get you two decimal positions also.
var oldNumber = 33, newNumber = 40;
var incr = (((newNumber - oldNumber)/oldNumber)*100).toFixed(2);
alert(incr);

Getting 6.33 from an equation in Javascript when it should output 8.99

I'm doing some simple math in Javascript, but my equation's result is drastically different than what it should be. The math is:
3.05+(((0.32*0)+3.28)+(1+(0.19*0))*(2.66*1^2))*1;
When I did it out by hand, and then used Wolfram Alpha (https://www.wolframalpha.com/) I get the correct result of 8.99. However, when I use the equation in Javascript I mysteriously get 6.33
The actual equation looks like
VO2move = VO2rest+(((C1*g2)+VO2walkmin)+(1+(C2*g2))*(C3*s2^2))*t2;
but I removed all the variables in an attempt to debug (I thought it might be some error where I needed parseInt)
Here are the whole functions for reference
function calc(){
var temp = 0;
var total = 0;
for(i = 0; i<sArr.length; i++){
total = total + calc2(i);
}
var o = document.getElementById("output");
o.value = total;
}
function calc2(i){
var s = document.getElementById("s"+i);
var g = document.getElementById("g"+i);
var t = document.getElementById("t"+i);
var VO2walkmin = 3.28;
var VO2rest = 3.05;
var C1 = 0.32;
var C2 = 0.19;
var C3 = 2.66;
var Cdecline = 0.73;
var s2 = s.value;
var g2 = g.value;
var t2 = t.value;
var negGrade = g.value;
if(g2 < 0){g2 = 0};
//VO2move = ((C1 * g2)+VO2walkmin)+((1+(C2*g2))*(C3*s2^2)); //ORIGINAL TRANSCRIPTION
//VO2move = VO2rest+(((C1*g2)+VO2walkmin)+(1+(C2*g2))*(C3*s2^2))*t2; // TRANSLATED FROM COPY PASTE
VO2move = 3.05+(((0.32*0)+3.28)+(1+(0.19*0))*(2.66*1^2))*1; // COPY - PASTED FROM EXCEL
return VO2move;
}
Even naked numbers I still get the output of 6.33. I'm totally puzzled, and any help is appreciated.
You need to take the power (exponentiation) operator ** instead of the bitwise XOR operator ^.
console.log(3.05+(((0.32*0)+3.28)+(1+(0.19*0))*(2.66*1**2))*1);

Financial calculation with JavaScript (What´s wrong?)

I'm trying to make a financial calculation, but there's something wrong.
JS Code:
function count (){
var coda = 1.500;
var codb = 15;
var codc = 0.06;
var codx = 1;
var result = (codc/codx(codx-((codx+codc)*-codb)))*coda;
alert(result);
}
Message: undefined
In this line
var result = (codc/codx(codx-((codx+codc)*-codb)))*coda;
You try to execute the 2nd codx as a function (codx()). I guess you miss an operand there.
Try for example:
var result = (codc/codx / (codx-((codx+codc)*-codb)))*coda;
You are missing a * operator, so the compiler tries to call codx as a function.
To fix your computation, add the * operator as follow:
function count (){
var coda = 1.500;
var codb = 15;
var codc = 0.06;
var codx = 1;
var result = (codc/codx * (codx - ((codx+codc)*-codb)))*coda;
// ^
alert(result);
}
Missing * symbol? codx is being used as a fuction as a result.
var coda = 1.500;
var codb = 15;
var codc = 0.06;
var codx = 1;
var result = (codc/codx*(codx-((codx+codc)*-codb)))*coda;
alert(result);
Slightly off-topic but you should never use floating point arithmetic in financial calculations. Instead calculate by integer cents and then format for viewing as you like.
In this case,
It is better to split the mathematical calculation.
Example:
function count (){
var coda = 1.500;
var codb = 15;
var codc = 0.06;
var codx = 1;
var res1 = ((codx+codc)*-codb);
var res2 = codx-res1;
var result = (codc/codx*res2)*coda;
alert(result);
}
var count = function () {
var coda = 1.5; var codb = 15; var codc = 0.06; var codx = 1;
var result = (codc/codx ** here ** (codx-((codx+codc)* - codb))) * coda;
console.log(result);
}
P.S you have to put something after codx it's seen by javascript as an undefined function.
If this relates to paying down a loan at interest i per payment period, then you get that after n payments at a rate of r the reduced principal is
p*(1+i)^n-r*(1+i)^n-r*(1+i)^(n-1)-...-r*(1+i)
=
p*(1+i)^n - (1+i)*((1+i)^n-1)/i*r
If that is to be zero, loan repaid, then the necessary rate computes as
r = i/((1+i)*(1-(1+i)^(-n))) * p
which is in some aspects similar, in other fundamental aspects different from your formula.
var p = 1.500;
var n = 15;
var i = 0.06;
var x = 1+i;
var result = i/( x*( 1-Math.pow(x,-n) ) )*p;
alert(result);

Javascript counting sum of price * quantity returns NaN

I have a problem with my code.
$('input[name="pocet"]').each(function(){
var $mnozstvo = parseInt($('this').val());
var $id = parseInt($(this).attr('id').substring(6));
var $aktualnyProdukt = $('#' + $id);
var $povodnaCena = parseFloat($aktualnyProdukt.data('price'));
var $riadkoveZlavy = $aktualnyProdukt.find('div .vypocetPreZlavu');
var $aktualnaCena = $povodnaCena;
if($riadkoveZlavy.length > 0) {
$riadkoveZlavy.each(function() {
$mnozstvoNaZlavu = parseInt($(this).data('mnozstvo'));
$cenaPoZlave = parseFloat($(this).data('cena'));
if($mnozstvo >= $mnozstvoNaZlavu) {
$aktualnaCena = $cenaPoZlave;
}
});
}
if(isNaN($mnozstvo)) $mnozstvo = 0;
total += $mnozstvo * $aktualnaCena;
});
However, after running this function, total returns NaN and I have no idea why. Could you help me?
HTML:
http://jsfiddle.net/UL7Sr/
var $mnozstvo = parseInt($('this').val()); should actually be var $mnozstvo = parseInt($(this).val());
Additionally, make sure that $aktualnaCena is a number. You do this for $mnozstvo, but not for $aktualnaCena. Try:
if(isNaN($mnozstvo)) $mnozstvo = 0;
if(isNaN($aktualnaCena)) $aktualnaCena = 0;
total += $mnozstvo * $aktualnaCena;
Also, please don't prefix all your variables with a $. JavaScript is not PHP. The convention when using jQuery is that you do that for jQuery element variables to distinguish from other variables. If you use it for all your variables in that context, it is actually confusing.
var $povodnaCena = parseFloat($aktualnyProdukt.data('price'));
var $povodnaCena = parseFloat($aktualnyProdukt.attr('data-price'));
Replacing the first line with the second one solved my problem.

Categories