Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get numeric value from a prompt box? [duplicate]

I was trying to do some simple mathematical calculations in HTML and jQuery and JavaScript, so I wanted to get input from user.
For input I tried doing this :

 var x = prompt("Enter a Value","0");
 var y = prompt("Enter a Value", "0");

But I am not able to perform any kind of calculations as these values are strings.
Please, can any one show me how to convert them into integers.

like image 861
user2627383 Avatar asked Jul 28 '13 10:07

user2627383


People also ask

How to convert prompt value to int in JavaScript?

var x = prompt("Enter a Value", "0"); var y = prompt("Enter a Value", "0"); var num1 = parseInt(x); var num2 = parseInt(y); After this you can perform which ever calculations you want on them.

What is parseInt prompt?

The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal. If radix is omitted, JavaScript assumes radix 10.

How do I know if a number is a prompt?

Typeof return value of prompt is always string. To check the typeof prompt first store it's value in a variable or else you could type - console. log(typeof prompt("Value")); But the type of prompt is always a string.


2 Answers

parseInt() or parseFloat() are functions in JavaScript which can help you convert the values into integers or floats respectively.

Syntax:

 parseInt(string, radix);
 parseFloat(string); 
  • string: the string expression to be parsed as a number.
  • radix: (optional, but highly encouraged) the base of the numeral system to be used - a number between 2 and 36.

Example:

 var x = prompt("Enter a Value", "0");
 var y = prompt("Enter a Value", "0");
 var num1 = parseInt(x);
 var num2 = parseInt(y);

After this you can perform which ever calculations you want on them.

like image 80
Anurag-Sharma Avatar answered Oct 23 '22 21:10

Anurag-Sharma


JavaScript will "convert" numeric string to integer, if you perform calculations on it (as JS is weakly typed). But you can convert it yourself using parseInt or parseFloat.

Just remember to put radix in parseInt!

In case of integer inputs:

var x = parseInt(prompt("Enter a Value", "0"), 10);
var y = parseInt(prompt("Enter a Value", "0"), 10);

In case of float:

var x = parseFloat(prompt("Enter a Value", "0"));
var y = parseFloat(prompt("Enter a Value", "0"));
like image 38
Tadeck Avatar answered Oct 23 '22 21:10

Tadeck