javascript 用户在文本字段中输入的数字的数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9280057/
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
numerical value of number input by user in a text field
提问by Akash
I need to add up two numbers input by the user. To do that, I create two input fields, retrieve values from them , using .val(), in two separate variables and then add them. The problem is that the strings are added and not the numbers. For eg. 2 + 3 becomes 23 and not 5. please suggest what to do, except using type = number in the input boxes.
我需要将用户输入的两个数字相加。为此,我创建了两个输入字段,在两个单独的变量中使用 .val() 从中检索值,然后添加它们。问题是添加的是字符串而不是数字。例如。2 + 3 变成 23 而不是 5。请建议怎么做,除了在输入框中使用 type = number 。
采纳答案by John Fisher
You can use parseInt(...)
您可以使用 parseInt(...)
Example:
例子:
var num = parseInt("2", 10) + parseInt("3", 10);
// num == 5
回答by Zeta
Use parseInt
to convert a string into a number:
使用parseInt
一个字符串转换成一个数字:
var a = '2';
var b = '3';
var sum = parseInt(a,10) + parseInt(b,10);
console.log(sum); /* 5 */
Keep in mind that parseInt(str, rad)
will only work if str
actually contains a number of base rad
, so if you want to allow other bases you'll need to check them manually. Also note that you'll need to use parseFloat
if you want more than integers.
请记住,parseInt(str, rad)
只有在str
实际包含多个 base时才有效rad
,因此如果您想允许其他 bases,您需要手动检查它们。另请注意,parseFloat
如果您想要多个整数,则需要使用。
回答by ndtreviv
Either use parseInt (http://www.w3schools.com/jsref/jsref_parseint.asp) or parseFloat (http://www.w3schools.com/jsref/jsref_parsefloat.asp) to convert to a numerical value before adding.
在添加之前使用 parseInt (http://www.w3schools.com/jsref/jsref_parseint.asp) 或 parseFloat (http://www.w3schools.com/jsref/jsref_parsefloat.asp) 转换为数值。
PS: This is the simple answer. You might want to do some validation/stripping/trimming etc.
PS:这是简单的答案。您可能想做一些验证/剥离/修剪等。