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.

Answers:

Answer

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.

Answer

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"));
Answer
var xInt = parseInt(x)

This will return either the integer value, or NaN.

Read more about parseInt here.

Answer

You have to use parseInt() to convert

For eg.

  var z = parseInt(x) + parseInt(y);

use parseFloat() if you want to handle float value.

Answer

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.

Answer

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)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.