javascript addition program displaying "NaN" error - javascript

My question is about this simple program always displaying a "NaN" error.
My code for this simple function will always alert a "NaN" error for a simple addition instruction and I'm not sure how to resolve this.
The program should simply add miles and the bonus, which is 1000 if futureTrips is any value greater than 0.
My code is:
var miles;
var futureTrips;
var totalMiles;
var bonus;
miles = prompt("Please enter your current miles");
futureTrips = prompt("pleae enter amount of future trips");
if (futureTrips > 0){
(bonus = 1000);}
else{
(bonus = 0);}
totalMiles = (bonus.value + miles.value);
alert(totalMiles);
This will always display a "NaN" error. Any tips on how to fix this issue?

Problem:
bonus and miles are numbers (miles in fact is a string). You have to use them not their .value property that doesn't exist (thus is undefined), so:
totalMiles = (bonus.value + miles.value);
is the same as:
totalMiles = (undefined + undefined);
which is NaN.
Fix:
Use bonus and miles directly (you still have to convert miles to a number though):
totalMiles = bonus + Number(miles);
Working snippett:
var miles;
var futureTrips;
var totalMiles;
var bonus;
miles = prompt("Please enter your current miles");
futureTrips = prompt("pleae enter amount of future trips");
futureTrips = Number(futureTrips);
if (futureTrips > 0) {
bonus = 1000;
} else {
bonus = 0;
}
totalMiles = bonus + Number(miles);
alert(totalMiles);
Notes:
prompt return strings, so you have to convert miles into a number first, otherwise you get a string concatenation instead of arithmitic addition. You don't have to convert bonus because it's already a number. You should also consider converting futureTrips to a number before the if.
Parenthesis are not necessary around expressions: (bonus = 1000); is equivalent to bonus = 1000;.

In JavaScript, prompt returns string value. You can not apply .value on them.
By default string values are converted to int before the addition with another integer (also known as coercing). But to be on the safe side you can use parseInt to convert string to int manually.
Change totalMiles = (bonus.value + miles.value); To
totalMiles = (bonus.value + parseInt(miles));

Try this:
var totalMiles;
var bonus;
var miles = parseInt(prompt("Please enter your current miles"),10);
var futureTrips = parseInt(prompt("pleae enter amount of future trips"),10);
if (futureTrips > 0) {
bonus = 1000;
} else {
bonus = 0;
}
totalMiles = bonus + miles;
alert(totalMiles);
I always use the radix in parseInt like paarseInt(miles,10). Or use parseFloat(miles).
Also don't use bonus.value or miles.value, just use miles since miles is the return string from then prompt command and bonus is a number.

miles is a string here. To get the value as an integer I suggest instead of miles.value do parseInt(miles)

Your code modified:
var miles;
var futureTrips;
var totalMiles;
var bonus;
do{
miles = prompt("Please enter your current miles") ; //assigns a string value to variable
futureTrips = prompt("pleae enter amount of future trips");
miles = parseInt(miles); //convert string to number
futureTrips = parseInt(futureTrips);
}while( isNaN(miles + futureTrips) ); //optional loop, repeat prompts if NaN detected
if (futureTrips > 0){
(bonus = 1000);}
else{
(bonus = 0);}
totalMiles = (bonus + miles); // removed bonus.value, did you mean to use the Object.ValueOf() method?
alert(totalMiles);

Related

How to get a JavaScript factorial programs' loop to show the working used?

Hello there I have been challenged to write a program in JavaScript despite not really knowing much about it that asks the user for a number and then calculates the factorial of that number. I used already asked questions and managed to get the calculation to work but couldn't get the required output. I have to get it in the following output without using any fancy libraries or extra variables/arrays (which I can't think of how to do) :
(assuming user input is 5):
The factorial of 5 is 5*4*3*2*1=120
OR
5! is 5*4*3*2*1=120
Here is the code I've got so far:
//prompts the user for a positive number
var number = parseInt(prompt("Please enter a positive number"));
console.log(number);
//checks the number to see if it is a string
if (isNaN(number)) {
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (number < 0) {
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorial = 1;
for (count = 1; count <= number; count++) {
factorial *= count;
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The factorial of " + number + " is " + factorial + ".");
}
I know there are many similar questions to this as I looked around and used them to help me get this far but it is getting the output into the required format that I'm struggling with. I am told it is possible with a loop but don't know where to begin implementing that and I'm only allowed to use that solution.
Unfortunately this is part of a larger program in the challenge and I can only use the following variables:
Number (variable initialised as 0 to hold user input)
Factorial (variable initialised to 1 to hold value of calculated factorial)
Count (variable to hold number of times loop is executed for performing factorial calculation)
Probably you just need to build a string in that loop (on top of calculating the actual value):
let input=parseInt(prompt("Number?"));
let output="";
let result=1;
for(let i=input;i>1;i--){
result*=i;
output+=i+"*";
}
console.log(input+"! is "+output+"1="+result);
The "no-array clause" in your task presumably means that you are not supposed to build an array and use join() on it, like
let arr=[1,2,3,4,5];
console.log(arr.join("*"));
I have updated your code mainly here, Also make sure you are using the same variable num in your code and not number:
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}
//prompts the user for a positive number
var num = parseInt(prompt("Please enter a positive number"));
console.log(num);
//checks the number to see if it is a string
if (isNaN(num))
{
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (num < 0)
{
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The " + num + "! is " + factorials.join('*') + " is " + result + ".");
}

Can't quite get two variables to add and subtract properly. (Javascript)

Currently I'm trying to use prompts to assign an integer to variables, and then add/subtract based on if the input is a negative or positive value, currently it will add, but it won't subtract.
var creditLimit = parseInt(prompt("What is your credit limit?"))
var initialBalance = parseInt(prompt("What is your current balance?"))
var balanceChange = parseInt(prompt("Please enter a charge or a credit amount"))
var newBalance
if (balanceChange > 0) {
newBalance = initialBalance + balanceChange;
} else if (balanceChange < 0) {
newBalance = initialBalance - balanceChange;
} else {
alert("Please enter a valid integer")
}
I know the alert could probably be something better, but right now I'm just breaking down a credit balance calculator and got held up at this spot.
else if (balanceChange < 0) {
newBalance = initialBalance - balanceChange;
}
The balanceChange < 0 i.e it will be a negative value, so initialBalance - (- balanceChange) = initialBalance + balanceChange
that causing the problem here.
Ah, I just figured it out, I suppose I was trying to use a double negative operation by subtracting a negative input!

control random number with javascript

This is my intent,
Generate random number
Store in variable
Clear variable
Generate new number greater than previous
Store in variable
I understand
(Math.floor(Math.random()*100)+1)
For 1-100 but not sure how to accomplish what I want exactly.
The following will generate a random number and then find the next random number it finds that is greater than it (or equal to it if it is greater than or equal to 99):
var num = Math.floor(Math.random()*100)+1;
alert(num); //current number
var newNum;
while((newNum = Math.floor(Math.random()*100)+1) < num && newNum < 100);
alert(newNum); //new number > num (or == num if num >= 99)
use
var ran_val = 1;
// ... some code goes here
ran_val = (Math.floor(Math.random()*100) + ran_val)
if you have no upper limit on the random numbers,
ran_val = (Math.floor(Math.random()*(100-ran_val)) + ran_val)
otherwise.
fwiw, the random numbers you emulate this way are no longer uniformly distributed.
var numb1 = Math.floor(Math.random()*100)+1, //Generate random number
numb2 = 0;
while (numb2<numb1) {
numb2 = Math.floor(Math.random()*100)+2; // Generate new number greater than previous
}
FIDDLE
You need to have a global variable and a function that handles the random number generation.
You can do something like this:
var num = 1;
function generaterandom(){
num = Math.floor(Math.random()*100)+num;
}

math.round vs parseInt

Have a quick JS question. What is the difference between math.round and parseInt?
I made a JS script to sum the inverses of prompted numbers:
<script type="text/javascript">
var numRep = prompt("How many repetitions would you like to run?");
var sum = 0;
var count = 0;
var i = 1; //variable i becomes 1
while (i <= numRep) {// repeat 5 times
var number = prompt("Please enter a non zero integer");
if(number==0){
document.write("Invalid Input <br>");
count++;
}
else{
document.write("The inverse is: " + 1/number + "<br>");
sum = sum + (1/parseInt(number)); //add number to the sum
}
i++; //increase i by 1
}
if (sum==0){
document.write("You did not enter valid input");}
else { document.write("The sum of the inverses is: " + sum); //display sum
}
</script></body></html>
and it uses parseInt. If I wanted to makeit use math.round, is there anything else I need to do so that It knows to limit the number of decimal places accordingly?
In other words, does math.round have to be formatted in a certain way?
The two functions are really quite different.
parseInt() extracts a number from a string, e.g.
parseInt('1.5')
// => 1
Math.round() rounds the number to the nearest whole number:
Math.round('1.5')
// => 2
parseInt() can get its number by removing extra text, e.g.:
parseInt('12foo')
// => 12
However, Math.round will not:
Math.round('12foo')
// => NaN
You should probably use parseFloat and Math.round since you're getting input from the user:
var number = parseFloat(prompt('Enter number:'));
var rounded = Math.round(number);
Math.round will round the number to the nearest integer. parseInt will assure you that the value is a number
So what you will need is something like this:
number = parseInt(number);
if ( isNan(number) || number == 0 ){
document.write("Invalid Input <br>");
count++;
}
This will assure you that the use has put in a number
Math.round expects a number, parseInt expects a string.
Use parseInt('12345', 10) for parsing 10-based numbers.
http://www.javascripter.net/faq/convert2.htm

Javascript: why does this produce and ugly string??? I would like currency

var total = 0;
$(".amount").each(function () {
var value = $(this).val();
value = (value.length < 1) ? 0 : value;
var tmp = parseFloat(value).toFixed(2);
total += tmp;
});
$(".total").text(total);
I am trying to loop through some text boxes and sum up their values. This produces a nasty string. What am I missing?? if I put 8 in the first textbox total text ends up as " 08.000.000.000.00". What am I doing wrong? I would like to format as currency but if not, at least just a two decimal number. Any pointers?
.toFixed converts the object from a Number to a String.
Leave the full values in place and only convert using .toFixed at the very end
$(".total").text(total.toFixed(2));
Alternatively, convert the string back to a number.
total = total + + tmp;
Just FYI, there is an excellent mathematical aggregation plugin for jQuery: jQuery Calculation
Using that plugin may also indirectly solve your issue.
It's usage would reduce your script to:
$('.total').text($('.amount').sum());
You are converting the parseFloat into a string, then adding it to total. Only add .toFixed(2) to the final line, once things have been added.
var total = 0;
$(".amount").each(function() {
var value = $(this).val();
value = (value.length < 1) ? 0 : value;
var tmp = parseFloat(value);
total += tmp;
});
$(".total").text(total).toFixed(2);

Categories