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.
This question is related to
javascript
jquery
html
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"));
You can use parseInt()
but, as mentioned, the radix (base) should be specified:
x = parseInt(x, 10);
y = parseInt(y, 10);
10 means a base-10 number.
See this link for an explanation of why the radix is necessary.
You have to use parseInt() to convert
For eg.
var z = parseInt(x) + parseInt(y);
use parseFloat() if you want to handle float value.
Working Demo Reading more Info
parseInt(x)
it will cast it into integer
x = parseInt(x);
x = parseInt(x,10); //the radix is 10 (decimal)
parseFloat(x)
it will cast it into float
Working Demo Reading more Info
x = parseFloat(x);
you can directly use prompt
var x = parseInt(prompt("Enter a Number", "1"), 10)
var xInt = parseInt(x)
This will return either the integer
value, or NaN
.
Read more about parseInt here.
Source: Stackoverflow.com