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.
Related
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();
I am currently learning JS and when I do some practice, I find some issues I am unclear on data type in Javascript. I understand that JS do NOT require specific type indication, it will automatically do the type conversion whenever possible. However, I suffer one problem when I do NOT do type conversion which is as follows:
var sum = 0;
function totalSum (a) {
if (a == 0) {
return sum;
}
else {
sum += a;
return totalSum(--a);
}
}
var i = prompt("Give me an integer");
// var num = parseInt(i);
alert("Total sum from 1 to " + i + " = " + totalSum(i));
// alert("Total sum from 1 to " + i + " = " + totalSum(num));
I notice that the code works perfectly if I change the data type from string to int using parseInt function, just as the comment in the code does. BUT when I do NOT do the type conversion, things are getting strange, and I get a final result of 054321, if I input the prompt value as 5. AND in a similar way, input of 3, gets 0321 and so on.
Why is it the case? Can someone explain to me why the totalSum will be such a number? Isn't javascript will automatically helps me to turn it into integer, in order for it to work in the function, totalSum?
The sample code can also be viewed in http://jsfiddle.net/hphchan/66ghktd2/.
Thanks.
I will try to decompose what's happening in the totalSum method.
First the method totalSum is called with a string as parameter, like doing totalSum("5");
Then sum += a; (sum = 0 + "5" : sum = "05") (note that sum become a string now)
then return totalSum(--a);, --a is converting the value of a to a number and decrement it's value. so like calling return totalSum(4);
Then sum += a (sum = "05" + 4 : sum = "054") ...
See the documentation of window.prompt: (emphasis mine)
result is a string containing the text entered by the user, or the value null.
I need to make sure that my string is a number and for doing that, I was using isNaN function and everything was working but I got a problem when I typed in my input field '0e1'.
I was wondering what's the best way to check if my string is a number and without scientific notation
Try using regex. Here are some examples. The result is null if no match was found.
alert("0e1".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // null
alert("1".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // 1
alert("-1".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // -1
alert("1.0".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // 1.0
alert("-1.5".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // -1.5
alert("-1.5 4".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // null
If you want your input to only be an integer or float do this instead;
var input = '0e1';
if(!isNaN(input) && (parseInt(input, 10).toString() == input || parseFloat(input).toString() == input)){
//This is a valid number
}
Actually, the method you are using is fine. You have one problem with your code:
isNaN() should be !isNaN(). Remember, isNaN() checks if the number is NotaNumber. `!isNaN() checks if it IS a number.
isNaN(0e1) should return false because 0e1 is a number! I know, it's kind of confusing.
!isNaN(0e1) will return TRUE because !isNan() checks if a value IS a number.
I hope this helps.
isNaN() function determines whether a value is an illegal number, so if it is not a number. The good thing about isNaN function is, that is suportet by all browsers (ch, ie, ff, op, sf).
function myFunction() {
var a = isNaN(123) + "<br>";
var b = isNaN(-1.23) + "<br>";
var c = isNaN(123-456) + "<br>";
var d = isNaN("Hello") + "<br>";
var e = isNaN("2014/11/19") + "<br>";
var result = a + b + c + d + e;
document.getElementById("test").innerHTML = result;
}
So result would be: If value is a number return "False" if is not a number return "True".
You can test it on JsFiddle: isNaN()
I'm getting a numeric value from a form. Then I check to see if it's NaN. If it is a number I want to set that value to a variable. The problem is that when I enter a valid number I still get an alert and the number isn't passed to the variable "date". How should I modify my statement so that when it is a valid number I can assign it to the variable date?
var adate = document.getElementById("dueDate").value;
if ( adate == NaN || " ") {
alert("Please enter a due date");
return;
}
else {
var date = (new Date()).setDate(adate);
}
processDate(date);
Use Javascript's isNaN() function.
Checking equality with NaN is always false, as per IEEE's standards.
Stephen Canon, a member of the IEEE-754 committee that decided this, has an excellent answer explaining this here.
As strange as it seems, NaN !== NaN.
if (adate !== adate || adate !== " ") {
//...
}
The isNaN function would work in a lot of cases. There is a good case to be made that it is broken, though.
One nice way of getting around this is:
MyNamespace.isNaN = function (x) {
return x !== x;
}
you could Use if( isNaN(adate))
good luck
You have two problems here. The result is that the conditional will always pass. This is what it does:
adate == NaN // first, test if adate == NaN (this always returns false)
|| // if the first test fails (i.e. always), carry on checking
" " // test if the string " " is truthy (this always returns true)
The || does two separate checks. It does not test to see if adate is "either NaN or " "", which seems to be what you expect.
Your code might as well say
if ( true ) {
You would be able to sort this out, however, if you tried two comparisons:
if ( (adate == NaN) || (adate === " ")) {
As other people have said, however, this doesn't work, because NaN !== NaN. So the solution is to use isNaN:
if (isNaN(adate) || (adate === " ")) {
By using isNaN method we can verify if the given input is number or not.
let num1 = parseInt(prompt('Enter your number-1'));
let num2 = parseInt(prompt('Enter your number-2'));
alert(num1 + " is of type " + typeof num1 + " & " + num2 + " is of type " + typeof num2);
if (isNaN(num1) || isNaN(num2)) {
alert("Can not add incompatible types");
} else {
let sum = num1 + num2;
alert("Sum is " + sum);
}
Which one of these to JS snippets are better in terms of style?
var answer = Number(prompt('What is the value of 2 + 2?'));
if (answer === 4) {
// do something
}
vs.
var answer = prompt('What is the value of 2 + 2?');
if (answer == 4) {
// do something
}
I'd say the first one is better because it is more explicit (and no type coercion will happen).
They are both wrong, because you should use parseInt(XX, 10) for this. And remember, every time you use == Jesus kills a puppy. So always use ===, and therefore: always check against the correct type.
It depends on what you want to do with answer. If the only thing you want to do is compare it, you don't need to convert the type:
var answer = prompt('What is the value of 2 + 2?');
if (answer === "4") {
// do something
}
If you want to end up with a number for comparison and then further processing, Number or the unary plus operator + will convert the output string to a numeric value, or NaN if it is not a valid base 10 number.
var answer = +prompt('What is the value of 2 + 2?');
if (answer === 4) {
// do something
}
There is a difference between parseInt(x, 10) and Number(x) - the former will ignore non-numeric characters at the end.
parseInt("4Hello World"); // 4
Number("4Hello World"); //NaN
+"4Hello World"; //NaN
Well of course the first one because, as you mentioned, no type coercion happens.but you should use parseInt:
var answer = parseInt((prompt('What is the value of 2 + 2?'), 10)) ;
Better would be
var n = prompt("What is the value of 2 + 2?");
n = parseInt(n, 10);
//and check