How do I restrict user input to only numbers in Javascript? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How do I restrict user input to only numbers in Javascript?

I'm new to javascript, so pardon my syntax. I am trying to create a 2 number alert box calculator in Javascript, other functions work fine except that Addition, e.g Instead of 1 + 3 = 4, it returns 13 instead (concatenation), would really appreciate if I can be shown what I'm doing wrong. Here's the code below: function addNum(){ var result = a + b; alert (result); } function subtractNum(){ var result = a - b; alert (result); } function multiplyNum(){ var result = a * b; alert (result); } function divideNum(){ var result = a / b; alert (result); } var calc = prompt ( "Choose any of these options for your calculation: \n'+' for Addition \n'-' for Subtraction \n'*' for Multiplication \n'/' for Division "); if (calc === "+"){ var a = prompt ("Enter first number: " ) var b = prompt ("Enter second number: " ) addNum(); } else if (calc === "-") { var a = prompt ("Enter first number: " ) var b = prompt ("Enter second number: " ) subtractNum(); } else if (calc === "*") { var a = prompt ("Enter first number: " ) var b = prompt ("Enter second number: " ) multiplyNum(); } else if (calc === "/") { var a = prompt ("Enter first number: " ) var b = prompt ("Enter second number: " ) divideNum(); } else{ alert("System could not perform operation") }

9th Mar 2020, 2:12 AM
Ifechi
Ifechi - avatar
19 Answers
+ 4
The addition is not working because <a> and <b> are inputs received from `prompt` which returns a string. + operator acts differently when dealing with string operands and numeric operands. + operator adds 2 operands when they are numbers, but + operator concatenates 2 operands when they are string, or either one of the operands were string. Hint: Follow Gordon's tips with handling string -> number conversions. P.S. Your code is truncated due to character limits. Next time, prefer to save the code in SoloLearn and share the link instead. Follow this guide if you didn't know yet, how to share links 👇 (Edited) https://www.sololearn.com/post/74857/?ref=app
9th Mar 2020, 5:40 AM
Ipang
+ 3
Hi! how to restrict input only to numbers I don't know this method. the user can enter anything, we can only try to catch numbers from there. keep in mind that the values you enter (even just numbers) will be in the form of a string. therefore, in order to perform any actions on them, you must convert them to a number. try using the parseInt() function
9th Mar 2020, 6:00 AM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 3
EmmanueL Z. (Zé) thanks for your feedback. Here is a table of values handled by Number : https://www.sololearn.com/post/115762/?ref=app As you can notice, some input will become NaN, and if we pass NaN to subtractions, it'll raise exception. https://www.sololearn.com/post/115377/?ref=app That's why we need to use isNaN to check if it is NaN after converting to number with Number() https://www.sololearn.com/post/133947/?ref=app https://code.sololearn.com/WKKkpq0efxai/?ref=app
10th Mar 2020, 3:06 AM
Gordon
Gordon - avatar
+ 3
carlos mercado If you use parseInt(), input like 5.5 will be truncated into 5. This is applicable to situation when the input must be integer (for example, index of an array) Because in this question, the asker needs to perform calculations on numbers, where there is no restriction that they must be integer, that's why Number() is preferred in the context of this question.
10th Mar 2020, 3:14 AM
Gordon
Gordon - avatar
+ 2
if you use <input> <input type="number"> prompt cannot restrict input to number, but you can validate. a = Number(a); If (Number.isNaN(a)) { alert("You must enter number!"); } else { .... }
9th Mar 2020, 4:18 AM
Gordon
Gordon - avatar
+ 2
Thank you very much Gordon, It worked👇. https://code.sololearn.com/W2hk9UnPVyr3 (Also thank you very much Yaroslav & Ipang)
9th Mar 2020, 10:41 AM
Ifechi
Ifechi - avatar
+ 2
Very good job! have you already studied cycles? here's an additional task to make your program a little better: make a check for entering numbers from the user in the loop, but with the ability to exit it at any time. that is after checking the input for numbers let the loop return back to the input window
9th Mar 2020, 11:06 AM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 1
and an additional question on the knowledge of JavaScript: why did you make the conversion from a string to a number only when adding? do you need to do this when multiplying, dividing, and subtracting? and why does everything work correctly then?
9th Mar 2020, 11:09 AM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 1
Why?
9th Mar 2020, 3:23 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 1
@Yaroslav I thought of adding that loop that returns it to the return window but I'm yet to fully understand Cycles. But I will get it fixed as soon as I can. Thanks very much for being here. I really appreciate.
9th Mar 2020, 3:25 PM
Ifechi
Ifechi - avatar
+ 1
Please, find answers on my questions, and you will be stronger in js. Note: if you want to pin user type @ and wait few seconds ( window with names will opened)
9th Mar 2020, 3:29 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 1
Nnebedum Favour Ifechukwu , Ipang, Gordon , Ярослав Вернигора(Yaroslav Vernigora) hi You can also convert your prompt value directly like that: var a=Number(prompt("enter a number :")) If you want to check the type: console.log(typeof a)
9th Mar 2020, 10:50 PM
EmmanueLZ.
EmmanueLZ. - avatar
+ 1
Ipang , and reading your comment makes me realize if you don't convert directly the prompt value , I think you could still add a + before the string variable received when used(as it is supposed to mean you'd like that number of type string to be used as a number): let a=prompt("enter a number") //a is type string let b=+a + +a; //Should be used as numbers... To be checked...
9th Mar 2020, 11:18 PM
EmmanueLZ.
EmmanueLZ. - avatar
+ 1
EmmanueL Z. (Zé) Thanks, but I think Gordon's way by using `Number()` is preferrable than using + sign in front of string. It's a matter of readability to me.
9th Mar 2020, 11:28 PM
Ipang
+ 1
Ipang , right and the + only change the type for the specific operation , then the variable keep its string type: https://code.sololearn.com/W74vF6LPSK65/?ref=app
9th Mar 2020, 11:40 PM
EmmanueLZ.
EmmanueLZ. - avatar
+ 1
Thanks everyone for the contribution. I have updated the code with a lot of changes, you can check it out here => https://code.sololearn.com/W2hk9UnPVyr3
15th May 2020, 11:21 AM
Ifechi
Ifechi - avatar
0
Yaroslav, the concatenating problem happens only with addition, the rest of the calculations output the correct answers.
9th Mar 2020, 3:22 PM
Ifechi
Ifechi - avatar
0
For integers, redefine the variables and their data types like this: var a = prompt ("..."); a = parseInt(a, 10); var b = prompt("..."); b = parseInt(b, 10); They will change from string to integer values.
10th Mar 2020, 3:06 AM
carlos mercado
carlos mercado - avatar
0
Actually I m really confused please anyone or Anybody help me tricks to learn coding ? please help me...
15th May 2020, 1:25 PM
Giri Bahu Sahukara
Giri Bahu Sahukara - avatar