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.
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.
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.
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.
parseInt() or parseFloat() are functions in JavaScript which can help you convert the values into integers or floats respectively.
parseInt(string, radix);
parseFloat(string);
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.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With