Producing NAN when i need the total - javascript

The program needs to generate a random number for the presentValue, months, and interest rate between .1-.10%.
When performing the final calculation I get NaN.
var count = 5;
function futureValue(presentValue, interest, months) {
var step1 = 1 + Number(interest);
var step2 = parseFloat(Math.pow(step1, months));
var step3 = presentValue * step2;
return "The future value is: " + step3;
}
for (i = 0; i < count; i++) {
var presentValue = Math.floor(Math.random() * 100)
var interest = ((Math.random() * .10 - 0.1) + .1).toFixed(2)
var months = Math.floor(Math.random() * 100)
futureValue(presentValue, interest, months)
console.log("The present value is: " + presentValue);
console.log("The interest rate is: " + interest);
console.log("The number of months is: " + months);
console.log(futureValue());
}

You need to pass in the arguments:
console.log(futureValue())
to
console.log(futureValue(presentValue,interest,months))

This line calculates the future value correctly, and does nothing with it.
futureValue(presentValue,interest,months);
This line returns calls the futureValue function with no parameters, which returns NaN and writes the result to the log.
console.log(futureValue());
What you should do is assign the value to a variable, and then log that value:
var futureVal = futureValue(presentValue,interest,months);
console.log(futureVal);
Or just:
console.log(futureValue(presentValue,interest,months));

You are calling futureValue() with no parameters. It returns NaN (Not a Number) because you are making calculations with "undefined" which indeed, is Not a Number,
Try:
var count = 5
function futureValue(presentValue,interest,months){
var step1 = 1 + Number(interest);
var step2 = parseFloat(Math.pow(step1,months));
var step3 = presentValue*step2;
return("The future value is: " + step3);
}
for (i=0;i<count;i++){
var presentValue = Math.floor(Math.random()*100)
var interest = ((Math.random()*.10-0.1)+.1).toFixed(2)
var months = Math.floor(Math.random()*100)
var fv = futureValue(presentValue,interest,months) //save your futureValue in a variable.
console.log("The present value is: " + presentValue);
console.log("The interest rate is: " + interest);
console.log("The number of months is: " + months);
console.log(fv)//log your calculated future value
}

That's because
return("The future value is: " + step3);
Is a string. So, it indeed, is not a number.
You should return JUST the number, then create the string.

Once you call futureValue(presentValue,interest,months) the value disappears. If you want to console.log the result you should store it in a variable and then console.log that.

Related

JavaScript program to convert binary to decimal

I am trying to make a program which is able to do both decimal to binary and binary to decimal conversions.
I am having trouble with the binary to decimal portion of the code. Forgive me as I know the coding is quite incomplete but I can't figure out where I am going wrong.
Currently I am getting partially correct output in the calculation field (ex. "there is a 1 in the value of (2^0)" and "there is a 2 in the value of (2^1)").
However, when I type 11 as decimal the calculation field is repeating the code twice
(ex. "there is a 1 in the value of (2^0)","there is a 2 in the value of (2^1)","there is a 1 in the value of (2^0)", "there is a 2 in the value of (2^1)").
Obviously it should only give those values once per number.
Also the output field for the actual binary number is incorrect as well, and some of the variables aren't utilized/not needed, but I have been trying to fix the problem of repeating values first before I worked on that.
Any help would be much appreciated!!
function convertByArray(bval) {
var rB = new Array();
var outstr = "";
var p, t, a, o;
o = 0;
for(var i=0; i<bval.length; i++) {
var b = bval.charCodeAt(i);
t = 2;
p = i;
a = t ** p;
if(a === t ** p) {
outstr += a;
}
var bV = b;
$("txtCalc").value += "There is a " + a + " in the value " + "(" + t + "^" + p + ")" + "\n";
o += 1;
b = bV;
$("txtOut").value = outstr;
}
}
You can simply your code if you access the most-significant bit of the bit-string by taking the length (minus one) and subtracting it from the current position. You can access string characters like an array.
var $txtCalc = $(".txtCalc");
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function binaryToDecimal(bval) {
var base = 2, result = 0;
for (var pos = 0; pos < bval.length; pos++) {
var bit = +bval[(bval.length - 1) - pos];
if (bit === 1) {
result += base ** pos;
}
var message = "There is a " + bit + " in the position (" + base + "^" + pos + ")";
$txtCalc.val($txtCalc.val() + message + "\n");
}
$txtOut.val(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />
<br />
<textarea class="txtCalc" rows="10" cols="60"></textarea>
Alternatively, you can simply your program to the following. In JavaScript, you can parse any number in any base and format to another base.
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function convertFromBaseToBase(number, fromBase, toBase) {
return parseInt(number, fromBase).toString(toBase);
}
function binaryToDecimal(bval) {
$txtOut.val(convertFromBaseToBase(bval, 2, 10));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />

How to hide the output if var = 0

1How to hide the output if var m1000 = 0, I want to hide the text1000 for example if i input less than 1000 in the field I want the text1000 or 0 * 1000 Bank Bill to disappear from the output line
function doMoneyExchange() {
var inp1 = parseInt(document.getElementById("input1").value);
var m1000 = parseInt(inp1 / 1000);
var text1000 = m1000 + " * 1000 Bank Bill <br>"
inp1 = inp1 % 1000;
if (m1000 == "0") {
("text1000").hide();
}
var m500 = parseInt(inp1 / 500);
var text500 = m500 + " * 500 Bank Bill <br>"
inp1 = inp1 % 500;
var m100 = parseInt(inp1 / 100);
var text100 = m100 + " * 100 Bank Bill <br>"
inp1 = inp1 % 100;
var out = text1000 + text500 + text100;
document.getElementById("output").innerHTML = out;
It looks like you are trying to use jQuery. Is that correct? ("text1000").hide(); is my evidence. If so, $("text1000").hide(); might work better.
Okay, you're using $.hide() incorrectly. This method is used to hide elements but your program is concatenating everything at the end into a single string, which is then output to an HTML element.
What you should do instead is initialize your string variables to an empty string and then assign them a value on the condition that corresponding number variable is greater than 0. For example,
var text1000 = "";
if(m1000 > 0) {
text1000 = m1000 + " * 1000 Bank Bill <br/>";
}
Rinse and repeat and your resulting output string should only contain lines for numbers greater than 0.
P.S. If you're intent on using string concatenation for your output, there's no need for multiple substring variables. This makes your code less easily maintained. Rather, consider using a single string variable and concatenating in parts rather than all at the end.
var outputString = "";
if(m1000 === "0") {
outputString = outputString.concat(m1000 + " * 1000 Bank Bill <br>";
}
if(m100 === "0") {
outputString = outputString.concat(m100 + " * 100 Bank Bill <br>";
}
// repeat
document.getElementById("output").innerHTML = outputString;

Why am i getting NaN error?

I have a program that reads a specific text file from a coding challenge that I've recieved and it takes the numbers and puts it into an array for me to solve a quadratic equation. When I go to display my answers I keep getting the NaN error on all of my values and I cant find where I messed up.
CODE
var lines = data[0].split("/n");
var numQuads = lines[0];
for (var i = 1; i < numQuads; i++){
var fields = lines[i].split(",");
var a = fields[0];
var b = fields[1];
var c = fields[2];
}
a = parseInt();
b = parseInt();
c = parseInt();
var discr = (b * b) - (4 * (a * c));
var sqrDiscr = Math.sqrt(discr);
var x = (-b + sqrDiscr) / (2*a);
var y = (-b - sqrDiscr) / (2*a);
var outputL = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has no real roots!";
var outputW = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has roots x = " + x + " and x = " + y;
if (discr >= 0) {
output += outputW + "\n";
}
else {
output += outputL + "\n\n";
}
You did not provide an argument to the parseInt function. It works like this: parseInt("2") for example. You probably want to use parseFloat instead of parseInt.
Another remark: your data array is undefined.
you have insert String in parseInt()
a = parseInt("67");
b = parseInt("3");
c = parseInt("2");
Should probably be:
a = parseInt(a);
b = parseInt(b);
c = parseInt(c);
the problem was var lines = data[0].split("/n");
I used the wrong character. It was supposed to be var lines = data[0].split("\n");
The problem is that you are not parsing anything with your parse int.
Take a look here for some docs on parseInt.
Anyway that's how it should look like in your code:
a = parseInt(a, 10);
b = parseInt(b, 10);
c = parseInt(c, 10);
d = parseInt(d, 10);
EDIT: following the suggestion of #d3l I looked into the parseInt parameters, according to this question there could be some unexpected behaviours of the parseInt function without adding the radix parameter. Hence I added it to my solution.
Assuming you are parsing integers we can specify 10 as base.

JavaScript stops execution half way and evaluates wrong answer?, Console.log is correct

I didn't think this was possible until console.log(); shown me that whats happening is impossible.
I can't understand how this is possible it's like those variables are being modified before code execution finishes.
I got this JavaScript code with debugging in it.
It's wrapped in this.
$('#buyAmountInput').keyup(function () {
var buyAmount = parseFloat($(this).val());
var totalPrice = 0;
var max = $(this).attr("max");
var min = $(this).attr("min");
if (buyAmount != $(this).val()) {
if (isNaN(buyAmount)) {
buyAmount = 1;
$(this).val('');
} else {
$(this).val(buyAmount);
}
} else {
if (buyAmount > max) {
buyAmount = max;
$(this).val(buyAmount);
} else if (buyAmount < min) {
buyAmount = min;
//$(this).val(buyAmount);
}
}
totalPrice = buyAmount * unitPrice;
//lots of code trimmed off here.
largessAmount = Math.round(buyAmount * largessRule.rebate) / 100;
////
console.log("Buy amount " + buyAmount + " LargessRebate " + largessRule.rebate);
console.log("Total Price " + totalPrice);
console.log("Largess Amount " + largessAmount);
console.log("New rate " + Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
console.log("No .moneyFormat() New rate " + Number(totalPrice / (buyAmount + largessAmount)));
console.log("( " + totalPrice + " / ( " + buyAmount + " + " + largessAmount + " ))");
////
$('#unitPrice').html(Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
});
Debug looks like this
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.71
No .moneyFormat() New rate 0.7083333333333334
( 4250 / (5000 + 1000))
function fastKeyListener content_script.js:208
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.00 //<- What happened here
No .moneyFormat() New rate 0.00008499830003399932 //<- What happened here
( 4250 / (5000 + 1000)) //<- Third line executed this will give good rate..
Even if the variables are global and this code is in a keypress up jQuery callback function.
The variables are printed before they are executed by console.log() and they are correct but the answer is dead wrong.
Here is the moneyFormat() which I don't think could be the problem could it?
var effective_bit = -2;
Number.prototype.moneyFormat = function () {
var num = this;
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * Math.pow(10, -effective_bit) + 0.50000000001);
cents = num % Math.pow(10, -effective_bit);
num = Math.floor(num / Math.pow(10, -effective_bit)).toString();
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + ', ' + num.substring(num.length - (4 * i + 3));
if (effective_bit < 0) {
if (cents < 10 && effective_bit == '-2') cents = "0" + cents;
money = (((sign) ? '' : '-') + num + '.' + cents);
} else {
money = (((sign) ? '' : '-') + num);
}
return money;
};
I didn't post the whole code as it's very large, but you can see it live here
Just put into the Unit to buy of 4999, then scroll to 5000 it's all good.. try putting like 5001 or 50000 it will reset it to 5000 and give wrong answer in the process.
EDIT:
could of simplified the question to why does the console.log() functions evaluate incorrect answer if the same equation generated with the same variables just 1 line after in execution after gives correct answer, even on calculator.
Like some quantum going on here, bear with me there is nothing I could have done from 1 line to another line during that code-execution no breakpoints were set nothing plus those callbacks are functions generated in their own sandbox I believe so they are like ajax threads all working to complete sooner or later they all work separately from each other, so nothing working together here to mess it up. What you think could possibly happen here? some temporarily corruption or something?
This occurs sometimes when doing claulations using string variables.
Try converting the buyAmount and any variable that came from HTML to number before any calculation.
You can use the Number() function or parseFloat().
http://jsfiddle.net/rcdmk/63qas2kw/1/

jQuery - choosing sum at random

I am creating a "whack-a-mole" style game for primary school children where they have to click on the correct number in correspondence to the sum given.
At the moment the program is generating addition sums like this.
function createPlusSum(total) {
console.log(total)
var int1 = Math.ceil(Math.random() * total);
var int2 = total - int1;
$('#target').html(int1 + ' + ' + int2 + ' = ?');
}
I have done this again for subtraction and it works, but I don't know where to go from here in regards to randomizing whether an addition or subtraction question is produced. Here is the function to produce a subtraction question.
function createTakeSum(total) {
console.log(total)
var int1 = Math.ceil(Math.random() * total);
var int2 = total + int1;
$('#target').html(int2 + ' - ' + int1 + ' = ?');
}
I use this to create the addition sums
createPlusSum(total);
How would I say I want
createPlusSum(total);
or
createTakeSum(total);
Try this:
function createSum() {
total = Math.ceil(Math.random() * 10);
if(Math.random() > 0.5)
{
createTakeSum(total);
} else {
createPlusSum(total)
}
}
I would use random numbers again:
var rand = Math.floor(Math.random()*2);
switch (rand) {
case 0:
createPlusSum(total);
break;
case 1:
createTakeSum(total);
break;
}
I am not suggesting that this is how you should do it, but I am merely providing an alternative answer for thoroughness. (Pardon me, if the code is wrong. I'm a bit rusty with JS.
{
0: createPlusSum,
1: createTakeSum
}[Math.floor(Math.random() * 2)](total);
you can assign functions to array fields and call them random.
var func = new Array();
func[0] = function createPlusSum(total) {....};
func[1] = function createTakeSum(total) {....};
var rand = Math.floor(Math.random() * func.length);
func[rand](total);
this should do the trick, plus you can add as many functions as you want, just append them to the "func"-array
Here's a script that creates a random "add" or "subtract" question within the given range, and posts the correct answer in the console.log:
<div id="target"></div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
var total = {low: 10, high: 30}; // range
jQuery(document).ready(function() {
var total = Math.floor(Math.random() * (total.high - total.low) + total.low);
var int1 = Math.floor(Math.random() * total);
var int2 = total - int1;
if (Math.random() > 0.5) { // add
var question = int1 + ' + ' + int2 + ' = ?';
var answer = total;
}
else { // subtract
var question = total + ' - ' + int1 + ' = ?';
var answer = int2;
}
$('#target').html(question);
console.log('Correct answer: ' + answer);
});
</script>
Here's the working jsFiddle example

Categories