检查一个值是否是 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:46:36  来源:igfitidea点击:

Check whether a value is a number in JavaScript or jQuery

javascriptjquery

提问by Hussy

Possible Duplicate:
Validate numbers in JavaScript - IsNumeric()

可能的重复:
在 JavaScript 中验证数字 - IsNumeric()

var miscCharge = $("#miscCharge").val();

I want to check misChargeis 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 isNaNit 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

希望它有效