This question already has answers here:
Why is typeof x never 'number' when x comes from the prompt function?
(4 answers)
Closed 5 years ago.
See code below. My question is, why do I need to use parseInt() on bill and tipPercent for the totalCost calculation when the use actually enters in an integer already?
function billTotal() {
var bill = prompt("How much was your meal?");
if (bill != parseInt(bill)) {
alert("You need to enter an integer");
return;
};
var tip = prompt("How much would you like to tip?");
if (tip != parseInt(tip)) {
alert("You need to enter a number");
return;
}
var tipPercent = bill * (tip / 100);
var totalCost = parseInt(bill) + parseInt(tipPercent);
alert("You're Meal Cost " + totalCost);
};
billTotal();
The result of window.prompt is always a string. You need to use parseInt if you want to work with it as an integer.
Please note that result is a string. That means you should sometimes cast the value given by the user. For example, if his answer should be a Number, you should cast the value to Number. var aNumber = Number(window.prompt("Type a number", ""));
Reference : https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
Usually, you need parseInt in order to convert a user input (prompt) to an integer and then does arithmetic operations using this value.
As it stated more formally here:
The parseInt() function parses a string argument and returns an
integer of the specified radix (the base in mathematical numeral
systems).
Your code could be refactored like below. Initially we parse the user input and provided that input is valid we proceed with the calculation.
function billTotal() {
var billStr = prompt("How much was your meal?");
var bill = parseInt(billStr,10);
if (!bill || bill < 0) {
alert("You entered an ivalid value for bill");
return;
};
var tipStr = prompt("How much would you like to tip?");
var tip = parseInt(tipStr,10);
if (!tip || tip < 0) {
alert("You entered an invalid value for tip");
return;
};
var tipPercent = bill * (tip / 100);
var totalCost = bill + tipPercent;
alert("You're Meal Cost " + totalCost);
};
billTotal();
Related
This question already has answers here:
How do I test for NaN? [duplicate]
(2 answers)
Closed last month.
When I put Character in prompt the character is printed...
var myNumber = prompt("What is your Number");
var myName = prompt("What is your name");
if (NaN != myNumber) {
document.write("My Number is " + myNumber + " ");
} else {
document.write("This Number is NaN ")
}
document.write("& My Name is " + myName);
First to all i'll check if the actual myNumber is an actual number
if (!myNumber || isNaN(+myNumber)) {
console.log("This Number is NaN ")
} else {
console.log("My Number is " + myNumber + " ");
}
You have to check if the number is a valid number, every time the user submits the prompt.
Using a while loop is also a very good idea.
let myNumber = parseInt(prompt('Enter a number'));
const myName = prompt('Enter your name');
while (isNaN(myNumber)) {
myNumber = parseInt(prompt('Please enter a valid number!'));
};
console.log(`myNumber is ${myNumber}`);
console.log(`myName is ${myName}`);
The while loop will continuously check to see if the input from the prompt can be converted into a number, without yielding NaN after the parseInt() function.
The string literals are just an easier way to concatenate the strings, especially when talking about using numbers and "+". It is simply a cleaner way. However both ways are possible.
This question already has answers here:
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Javascript: "+" sign concatenates instead of giving sum of variables
(4 answers)
Closed 5 years ago.
This is returning 2 strings when i am trying to a 2 intergers. this is probably a really easy question!
thanks
<script>
function add() {
var noO = prompt("please enter a number:");
var noT = prompt("please enter a second number:");
var no1 = noO;
var no2 = noT;
var res = no1 + no2;
alert("the adiition of thoes 2 numbers is: " + res);
}
</script>
You need to use parseInt on no1 and no2 like follows:
var noO = prompt("please enter a number:");
var noT = prompt("please enter a second number:");
var no1 = noO;
var no2 = noT;
var res = parseInt(no1, 10) + parseInt(no2, 10);
alert("the adiition of thoes 2 numbers is: " + res);
EDIT
In addition, it is probably worth noting that parseInt should always be used with a radix specified based on the required behaviour:
An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10
E.g. a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal.. There are many examples on the web page link above.
function add() {
var noO = parseInt(prompt("please enter a number:"));
var noT = parseInt(prompt("please enter a second number:"));
var no1 = noO;
var no2 = noT;
var res = no1 + no2;
alert("the adiition of thoes 2 numbers is: " + res);
}
I'm trying to make a simple addition tool to add 2 values together, I'm just having a little trouble with the NaN checking... would like to print "Please insert numbers only" if either A or B, or both are NaN.
function getTotal() {
var a = parseInt(document.addBoxes.boxA.value);
var b = parseInt(document.addBoxes.boxB.value);
if (total != NaN) {
total = a+b;
document.getElementById("total").innerHTML = "The sum is " + total + ".";
}
else if (a === NaN || b === NaN){
document.getElementById("total").innerHTML = "Please insert numbers only.";
}
else if (a === NaN && b === NaN){
document.getElementById("total").innerHTML = "Please insert numbers only.";
}
};
Also, if there is a performance-friendly way to do this, or a better method.
Thanks!
Checking each individual value for NaN is not required.
function getTotal() {
var a = parseInt(document.addBoxes.boxA.value);
var b = parseInt(document.addBoxes.boxB.value);
var total = a + b;
if (!isNaN(total)) {
document.getElementById("total").innerHTML = "The sum is " + total + ".";
} else {
document.getElementById("total").innerHTML = "Please insert numbers only.";
}
}
Several problems in your code.
Line 4: if (total != NaN) {
total hasn't been defined yet. You should define it in a var beforehand if you don't want to leak globals.
var total = a + b;
Also, NaN will never equal itself so this kind of equality is dangerous. Either use the built-in isNaN() function to check for NaN or (since you mentioned performance-friendly) you can skip the function invocation and use:
if (total !== total) {
Since NaN is the only thing in javascript that doesn't equal itself. Notice I'm using a strict not-equals, we don't want any coercion. This might be a bit too abstract and people who look at the code later (including yourself) might have forgotten this unique property of NaN so I'd prefix this conditional with a comment and perhaps a link to the MDN - Necessity of isNaN page.
Your code might end up looking something like simonzack's answer.
I am defining a function that takes three numbers as arguments and returns the largest of them.
Here is my code:
var instructions = alert("Choose a set of numbers to input for the computer to determine which value is the largest");
var inputOne = prompt("Please input your first desired value");
var inputTwo = prompt("Please input your second desired value");
// THIS ARRAY STORES THE VALUES OF inputOne && inputTwo
var maxInput = Math.max([inputOne, inputTwo]);
var inputThree = prompt("Please input your third desired value");
// THIS WILL COMPARE BETWEEN THE inputThree && THE MAX INPUT OF THE USERS FIRST TWO CHOICES
var maxNumber = Math.max(maxInput, inputThree);
//validate if inputs are numbers and not letters
// isNaN()
var compare = function (maxNumber, inputThree) {
if (inputThree === maxNumber) {
return alert("The result is the same!");
} else if (inputThree != maxNumber) {
return alert(maxNumber + " " + "is the larger value!");
}
}
compare(maxNumber, inputThree);
Now I'm getting a result of "NaN is the larger value!" and it's driving me crazy! I tried running console.log to see where I'm getting NaN but that didn't work at all. All that did was log NaN to the console.
I also tried taking the parameters out of Math.max( ) however was just getting:
"-infinity is the larger value!"
Can someone at least give me a hint as to why this is happening? Or explain to me further what is going on.
Math.max([inputOne, inputTwo]) should be Math.max(inputOne, inputTwo)
Why don't you just get the largest of all of them with just
var maxNumber = Math.Max(inputOne, inputTwo, inputThree);
Here:
var inputThree = prompt("Please input your third desired value");
inputThree is a String (i.e. its value has a Type of String), always. And here:
var maxNumber = Math.max(maxInput, inputThree);
maxNumber is a Number, always (because that's what Math.max returns, even though the arguments are Strings). So:
inputThree === maxNumber
is always false, because a Number is never equal to a String (see the Strict Equality Comparison Algorithm). So either convert inputThree to a Number, e.g.
+inputThree === maxNumber
or use ==.
inputThree == maxNumber
I am making a simple tip calculator to help myself learn Javascript. The problem I can't solve is how to compensate for "bad input".
In the code below if the user prefaces the numeric input amount with a dollar sign $, the result is NAN.
function tipAmount(){
var dinner=prompt("How much was dinner?");
result = dinner*.10;
alert("Your tip is " +"$"+result );
}
How do I fix that.
You can try to parse out the numeric value with a regular expression:
var match = dinner.match(/\d+\.?\d*/); // parse with a regular expression
if(!match) { // not able to parse
alert("wrong");
}
var price = +match[0]; // convert to a number
result = price * .10;
The regular expression /\d+\.?\d*/ means: one or more digits, and possibly a dot with other digits following. This means that if e.g. dinner is "$1.23", price will be the number 1.23. The same goes for "$ 1.23" or "1.23 dollar" etc - the number will be parsed out with the pattern defined by the regular expression.
The simplest way would be to parse the input into a float, and see if NaN is returned.
if (isNaN(parseFloat(dinner)))
alert("Bad Input")
Just note that 45.2WWW will return 45.2, and so the above will pass.
If you want to make sure what the user typed in is exactly a number, you could do something like this:
var str = '3.445';
var num = parseFloat(str);
if (isNaN(num) || str.length !== num.toString().length)
alert("Bad Input");
try to parse the input as float or integer depending on your needs:
var dinner = parseFloat(prompt("How much was dinner?"));
or
var dinner = parseInt(prompt("How much was dinner?"));
this functions return 0 whether they unable to parse the input as number
Given your approach of using alerts, the following will work:
function tipAmount() {
var dinner=prompt("How much was dinner?");
//convert "dinner" to a number, stripping out any non numeric data
dinner = Number(dinner.replace(/[^0-9\.]+/g,""));
//any unknown data will convert to 0
if(dinner <= 0) {
alert("Please enter a valid amount");
return false;
}
var result = dinner*.10;
alert("Your tip is " +"$"+result );
return true;
}
Please tip more!
Just check if the value is numeric - Javascript's isNaN:
if (isNaN(dinner)) {
alert('Bad number, bub.');
return;
}
Or, if you want to allow users to type in both - just number or an amount with $ at the beginning, you can check for first char:
if( dinner.charAt(0) == '$' )
{
dinner = dinner.substring(1);
}
This way, whenever user types $, your app will just remove it. If they type a normal number it will calculate the tip for you...