jQuery 如何从提示框中获取数值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17907455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get numeric value from a prompt box?
提问by user2627383
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 :
我试图用 HTML、jQuery 和 JavaScript 做一些简单的数学计算,所以我想从用户那里获得输入。
对于输入,我尝试这样做:
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.
但我无法执行任何类型的计算,因为这些值是字符串。
拜托,任何人都可以告诉我如何将它们转换为整数。
回答by Anurag-Sharma
parseInt()or parseFloat()are functions in JavaScript which can help you convert the values into integers or floats respectively.
parseInt()或parseFloat()是 JavaScript 中的函数,可以帮助您将值分别转换为整数或浮点数。
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.
- string:要解析为数字的字符串表达式。
- 基数:(可选,但强烈鼓励)要使用的数字系统的基数 - 2 到 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.
在此之后,您可以对它们执行任何您想要的计算。
回答by Tadeck
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
.
如果您对其执行计算(因为 JS 是弱类型的),JavaScript 会将数字字符串“转换”为整数。但是您可以使用parseInt
或自己转换它parseFloat
。
Just remember to put radix in parseInt
!
只要记住把基数放进去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"));
回答by Raul Rene
var xInt = parseInt(x)
This will return either the integer
value, or NaN
.
这将返回integer
值,或NaN
。
Read more about parseInt here.
在此处阅读有关parseInt 的更多信息。
回答by Andy G
回答by Tushar Gupta - curioustushar
parseInt(x)
it will cast it into integer
parseInt(x)
它会将其转换为整数
x = parseInt(x);
x = parseInt(x,10); //the radix is 10 (decimal)
parseFloat(x)
it will cast it into float
parseFloat(x)
它会将其转换为浮点数
x = parseFloat(x);
you can directly use prompt
你可以直接使用 prompt
var x = parseInt(prompt("Enter a Number", "1"), 10)
回答by Uttam K C
You have to use parseInt() to convert
你必须使用 parseInt() 来转换
For eg.
例如。
var z = parseInt(x) + parseInt(y);
use parseFloat() if you want to handle float value.
如果要处理浮点值,请使用 parseFloat()。