检查一个值是否是 JavaScript 或 jQuery 中的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6449611/
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
Check whether a value is a number in JavaScript or jQuery
提问by Hussy
Possible Duplicate:
Validate numbers in JavaScript - IsNumeric()
var miscCharge = $("#miscCharge").val();
I want to check misCharge
is number or not. Is there any method or easy way in jQuery or JavaScript to do this?
我想检查misCharge
是不是数字。在 jQuery 或 JavaScript 中是否有任何方法或简单的方法来做到这一点?
HTMl is
HTML是
<g:textField name="miscCharge" id ="miscCharge" value="" size="9" max="100000000000" min="0" />
回答by zad
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
回答by cwallenpoole
You've an number of options, depending on how you want to play it:
您有多种选择,具体取决于您想如何玩:
isNaN(val)
Returns true if val is not a number, false if it is. In your case, this is probably what you need.
如果 val 不是数字,则返回 true,如果是,则返回 false。就您而言,这可能就是您所需要的。
isFinite(val)
Returns true if val, when cast to a String, is a number and it is not equal to +/- Infinity
如果 val 在转换为 String 时是一个数字并且它不等于 +/- Infinity,则返回 true
/^\d+$/.test(val)
Returns true if val, when cast to a String, has only digits (probably not what you need).
如果 val 在转换为 String 时只有数字(可能不是您需要的),则返回 true。
回答by Buffon
there is a function called isNaN
it return true if it's (Not-a-number) , so u can check for a number this way
isNaN
如果它是 (Not-a-number) ,则有一个称为它的函数返回 true,因此您可以通过这种方式检查数字
if(!isNaN(miscCharge))
{
//do some thing if it's a number
}else{
//do some thing if it's NOT a number
}
hope it works
希望它有效