JavaScript中的(内置)方式来检查字符串是否为有效数字

这篇博客探讨了JavaScript中检查字符串是否为有效数字的各种方法,包括使用isNaN、parseInt、正则表达式和Number构造函数。文章还讨论了各种边缘情况,如空字符串、科学计数法和浮点数,并提供了示例代码。
摘要由CSDN通过智能技术生成

我希望在与旧的VB6 IsNumeric()函数相同的概念空间中有东西吗?


#1楼

引用:

isNaN(num)//如果变量不包含有效数字,则返回true

如果您需要检查前导/后缀空格,例如,当需要一定数量的数字,并且需要输入例如“ 1111”而不是“ 111”或“ 111”时,则并非完全正确输入。

更好地使用:

var num = /^\d+$/.test(num)

#2楼

尝试isNan函数

isNaN()函数确定一个值是否为非法数字(非数字)。

如果该值等于NaN,则此函数返回true。 否则,它返回false。

此函数不同于Number特定Number.isNaN()方法。

全局isNaN()函数,将测试的值转换为Number,然后对其进行测试。

Number.isNan()不会将值转换为Number,并且对于任何非Number类型的值也不会返回true。


#3楼

parseInt(),但请注意此函数在某种意义上有所不同,例如,它为parseInt(“ 100px”)返回100。


#4楼

您可以使用RegExp方式:

var num = "987238";

if(num.match(/^-{0,1}\d+$/)){
  //valid integer (positive or negative)
}else if(num.match(/^\d+\.\d+$/)){
  //valid float
}else{
  //not valid number
}

#5楼

要检查变量(包括字符串)是否是数字,请检查它是否不是数字:

无论变量内容是字符串还是数字,这都有效。

isNaN(num)         // returns true if the variable does NOT contain a valid number

例子

isNaN(123)         // false
isNaN('123')       // false
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true
isNaN('10px')      // true

当然,您可以根据需要对此进行否定。 例如,要实现您提供的IsNumeric示例:

function isNumeric(num){
  return !isNaN(num)
}

要将包含数字的字符串转换为数字:

仅当字符串包含数字字符时才有效,否则返回NaN

+num               // returns the numeric value of the string, or NaN 
                   // if the string isn't purely numeric characters

例子

+'12'              // 12
+'12.'             // 12
+'12..'            // Nan
+'.12'             // 0.12
+'..12'            // Nan
+'foo'             // NaN
+'12px'            // NaN

将字符串宽松地转换为数字

有助于将“ 12px”转换为12,例如:

parseInt(num)      // extracts a numeric value from the 
                   // start of the string, or NaN.

例子

parseInt('12')     // 12
parseInt('aaa')    // NaN
parseInt('12px')   // 12
parseInt('foo2')   // NaN      These last two may be different
parseInt('12a5')   // 12       from what you expected to see. 

浮点数

请记住,与+num不同, parseInt (顾名思义)将通过截取小数点后的所有内容将浮点数转换为整数(如果由于这种行为想使用parseInt() ,则可能更好)使用另一种方法代替 ):

+'12.345'          // 12.345
parseInt(12.345)   // 12
parseInt('12.345') // 12

空字符串

空字符串可能有点违反直觉。 +num将空字符串转换为零,并且isNaN()假定相同:

+''                // 0
isNaN('')          // false

但是parseInt()不同意:

parseInt('')       // NaN

#6楼

旧问题,但给出的答案中缺少几点。

科学计数法。

!isNaN('1e+30')true ,但是在大多数情况下,当人们要求输入数字时,他们不想匹配1e+30类的东西。

较大的浮点数可能会表现出怪异

观察(使用Node.js):

> var s = Array(16 + 1).join('9')
undefined
> s.length
16
> s
'9999999999999999'
> !isNaN(s)
true
> Number(s)
10000000000000000
> String(Number(s)) === s
false
>

另一方面:

> var s = Array(16 + 1).join('1')
undefined
> String(Number(s)) === s
true
> var s = Array(15 + 1).join('9')
undefined
> String(Number(s)) === s
true
>

因此,如果期望String(Number(s)) === s ,那么最好将您的字符串最多限制为15位(省略前导零)。

无穷

> typeof Infinity
'number'
> !isNaN('Infinity')
true
> isFinite('Infinity')
false
>

鉴于所有这些,请检查给定的字符串是否是一个满足以下所有条件的数字:

  • 非科学记数法
  • 可预测的转换为Number然后返回String
  • 有限

这不是一件容易的事。 这是一个简单的版本:

  function isNonScientificNumberString(o) {
    if (!o || typeof o !== 'string') {
      // Should not be given anything but strings.
      return false;
    }
    return o.length <= 15 && o.indexOf('e+') < 0 && o.indexOf('E+') < 0 && !isNaN(o) && isFinite(o);
  }

但是,即使这一步也远远不够。 此处不处理前导零,但它们会拧长长度测试。


#7楼

PFB的工作解决方案:

 function(check){ 
    check = check + "";
    var isNumber =   check.trim().length>0? !isNaN(check):false;
    return isNumber;
    }

#8楼

如果您只是想检查字符串是否为整数(无小数点),则正则表达式是一种不错的选择。 诸如isNaN类的其他方法对于如此简单的事物而言过于复杂。

function isNumeric(value) {
    return /^-{0,1}\d+$/.test(value);
}

console.log(isNumeric('abcd'));         // false
console.log(isNumeric('123a'));         // false
console.log(isNumeric('1'));            // true
console.log(isNumeric('1234567890'));   // true
console.log(isNumeric('-23'));          // true
console.log(isNumeric(1234));           // true
console.log(isNumeric('123.4'));        // false
console.log(isNumeric(''));             // false
console.log(isNumeric(undefined));      // false
console.log(isNumeric(null));           // false

要只允许整数使用此:

function isNumeric(value) {
    return /^\d+$/.test(value);
}

console.log(isNumeric('123'));          // true
console.log(isNumeric('-23'));          // false

#9楼

在我的应用程序中,我们仅允许使用AZ AZ和0-9字符。 我发现使用“ 字符串 %1 === 0”的上述答案有效,除非字符串以0xnn开头(例如0x10),然后在我们不希望使用字符串时将其返回为数字。 在我们的数字检查中,以下简单的陷阱似乎可以解决我们的特定情况。

function isStringNumeric(str_input){   
    //concat a temporary 1 during the modulus to keep a beginning hex switch combination from messing us up   
    //very simple and as long as special characters (non a-z A-Z 0-9) are trapped it is fine   
    return '1'.concat(str_input) % 1 === 0;}

警告 :这可能是利用Javascript和Actionscript [Number(“ 1” + the_string)%1 === 0)]中的一个长期错误,我不能代表这个,但这正是我们所需要的。


#10楼

我的解决方案:

// returns true for positive ints; 
// no scientific notation, hexadecimals or floating point dots

var isPositiveInt = function(str) { 
   var result = true, chr;
   for (var i = 0, n = str.length; i < n; i++) {
       chr = str.charAt(i);
       if ((chr < "0" || chr > "9") && chr != ",") { //not digit or thousands separator
         result = false;
         break;
       };
       if (i == 0 && (chr == "0" || chr == ",")) {  //should not start with 0 or ,
         result = false;
         break;
       };
   };
   return result;
 };

您可以在循环内添加其他条件,以满足您的特定需求。


#11楼

将参数传递给构造函数时,可以使用Number的结果。

如果参数(字符串)不能转换为数字,则返回NaN,因此您可以确定所提供的字符串是否为有效数字。

注意:当传递空字符串或'\\t\\t''\\n\\t'作为数字时,将返回0; 传递true将返回1,而false则返回0。

    Number('34.00') // 34
    Number('-34') // -34
    Number('123e5') // 12300000
    Number('123e-5') // 0.00123
    Number('999999999999') // 999999999999
    Number('9999999999999999') // 10000000000000000 (integer accuracy up to 15 digit)
    Number('0xFF') // 255
    Number('Infinity') // Infinity  

    Number('34px') // NaN
    Number('xyz') // NaN
    Number('true') // NaN
    Number('false') // NaN

    // cavets
    Number('    ') // 0
    Number('\t\t') // 0
    Number('\n\t') // 0

#12楼

我的尝试有些混乱,但不是最好的解决方案

function isInt(a){
    return a === ""+~~a
}


console.log(isInt('abcd'));         // false
console.log(isInt('123a'));         // false
console.log(isInt('1'));            // true
console.log(isInt('0'));            // true
console.log(isInt('-0'));           // false
console.log(isInt('01'));           // false
console.log(isInt('10'));           // true
console.log(isInt('-1234567890'));  // true
console.log(isInt(1234));           // false
console.log(isInt('123.4'));        // false
console.log(isInt(''));             // false

// other types then string returns false
console.log(isInt(5));              // false
console.log(isInt(undefined));      // false
console.log(isInt(null));           // false
console.log(isInt('0x1'));          // false
console.log(isInt(Infinity));       // false

#13楼

如果确实要确保字符串仅包含数字,任何数字(整数或浮点数)以及正好是数字, 则不能使用parseInt() / parseFloat()Number()!isNaN()他们自己。 请注意,当Number()返回数字时, !isNaN()实际上返回true ,而当其返回NaN时实际上返回false ,因此我将在其余的讨论中将其排除。

这个问题parseFloat()是,它会返回一个数字,如果字符串中包含任何数量,即使字符串不只是准确一些包含:

parseFloat("2016-12-31")  // returns 2016
parseFloat("1-1") // return 1
parseFloat("1.2.3") // returns 1.2

Number()的问题在于,如果传递的值根本不是数字,它将返回一个数字!

Number("") // returns 0
Number(" ") // returns 0
Number(" \u00A0   \t\n\r") // returns 0

滚动自己的正则表达式的问题在于,除非您创建了与浮点数匹配的确切正则表达式,否则Javascript会识别该正则表达式,否则您会错过某些情况,或者会发现本不应该的情况。 即使您可以使用自己的正则表达式,为什么呢? 有更简单的内置方法。

但是,事实证明,对于parseFloat()在不应该返回数字的情况下, Number() (和isNaN() )都会做正确的事情,反之亦然。 因此,要找出一个字符串是否确实是唯一且仅是一个数字,请调用这两个函数并查看它们是否返回true:

function isNumber(str) {
  if (typeof str != "string") return false // we only process strings!
  // could also coerce to string: str = ""+str
  return !isNaN(str) && !isNaN(parseFloat(str))
}

#14楼

如果有人失望了,我会花一些时间来破解这个补丁,尝试对moment.js( https://github.com/moment/moment )进行修补。 这是我从中拿走的东西:

function isNumeric(val) {
    var _val = +val;
    return (val !== val + 1) //infinity check
        && (_val === +val) //Cute coercion check
        && (typeof val !== 'object') //Array/object check
}

处理以下情况:

真正! :

isNumeric("1"))
isNumeric(1e10))
isNumeric(1E10))
isNumeric(+"6e4"))
isNumeric("1.2222"))
isNumeric("-1.2222"))
isNumeric("-1.222200000000000000"))
isNumeric("1.222200000000000000"))
isNumeric(1))
isNumeric(0))
isNumeric(-0))
isNumeric(1010010293029))
isNumeric(1.100393830000))
isNumeric(Math.LN2))
isNumeric(Math.PI))
isNumeric(5e10))

假! :

isNumeric(NaN))
isNumeric(Infinity))
isNumeric(-Infinity))
isNumeric())
isNumeric(undefined))
isNumeric('[1,2,3]'))
isNumeric({a:1,b:2}))
isNumeric(null))
isNumeric([1]))
isNumeric(new Date()))

具有讽刺意味的是,我最努力的一个:

isNumeric(new Number(1)) => false

任何建议欢迎。 :]


#15楼

也许有一个或两个遇到这个问题的人需要比平时更严格的检查(就像我一样)。 在这种情况下,这可能会很有用:

if(str === String(Number(str))) {
  // it's a "perfectly formatted" number
}

谨防! 这将拒绝像琴弦.140.00008000.1 。 这非常挑剔-字符串必须与数字的“ 最最小完美形式 ”匹配,此测试才能通过。

它使用StringNumber构造函数将字符串转换为数字,然后再次返回,从而检查JavaScript引擎的“完美最小形式”(使用初始Number构造函数将其转换为最小形式)是否与原始字符串匹配。


#16楼

我已经测试过,迈克尔的解决方案是最好的。 投票给他上面的答案(在该页面上搜索“如果您确实要确保该字符串”以找到它)。 本质上,他的答案是这样的:

function isNumeric(num){
  num = "" + num; //coerce num to be a string
  return !isNaN(num) && !isNaN(parseFloat(num));
}

它适用于每个测试用例,我在这里记录了这些内容: https : //jsfiddle.net/wggehvp9/5/

对于这些边缘情况,许多其他解决方案均失败:'',null,“”,true和[]。 从理论上讲,您可以通过适当的错误处理来使用它们,例如:

return !isNaN(num);

要么

return (+num === +num);

对/ \\ s /,null,“”,true,false,[](还有其他?)进行特殊处理


#17楼

为什么jQuery的实现不够好?

function isNumeric(a) {
    var b = a && a.toString();
    return !$.isArray(a) && b - parseFloat(b) + 1 >= 0;
};

迈克尔提出了类似的建议(尽管我在这里偷了“ user1691651-约翰”的变更版):

function isNumeric(num){
    num = "" + num; //coerce num to be a string
    return !isNaN(num) && !isNaN(parseFloat(num));
}

以下是最有可能性能较差但结果稳定的解决方案。 这是jQuery 1.12.4实现和Michael的回答的矛盾之处,需要额外检查前导/后缀空格(因为Michael的版本对于前导/后缀空格的数字返回true):

function isNumeric(a) {
    var str = a + "";
    var b = a && a.toString();
    return !$.isArray(a) && b - parseFloat(b) + 1 >= 0 &&
           !/^\s+|\s+$/g.test(str) &&
           !isNaN(str) && !isNaN(parseFloat(str));
};

不过,后一个版本具有两个新变量。 通过执行以下操作,可以绕开其中之一:

function isNumeric(a) {
    if ($.isArray(a)) return false;
    var b = a && a.toString();
    a = a + "";
    return b - parseFloat(b) + 1 >= 0 &&
            !/^\s+|\s+$/g.test(a) &&
            !isNaN(a) && !isNaN(parseFloat(a));
};

除了手动测试我将在当前困境中遇到的几个用例(这都是非常标准的东西)以外,我还没有通过其他方式对这些中的任何一个进行过测试。 这是“站在巨人的肩膀上”的情况。


#18楼

您可以像使用流librar y一样使用类型,以获取静态的编译时检查。 当然,对于用户输入而言并不是十分有用。

// @flow

function acceptsNumber(value: number) {
  // ...
}

acceptsNumber(42);       // Works!
acceptsNumber(3.14);     // Works!
acceptsNumber(NaN);      // Works!
acceptsNumber(Infinity); // Works!
acceptsNumber("foo");    // Error!

#19楼

这是检查sNum是否为有效数值的sNum ; 它已针对多种输入进行了测试:

!isNaN(+s.replace(/\s|\$/g, ''));  // returns True if numeric value

#20楼

我喜欢这个简单。

Number.isNaN(Number(value))

上面是普通的Javascript,但我将其与TypeScript Typeguard结合使用以进行智能类型检查。 这对于打字稿编译器为您提供正确的智能提示且没有类型错误非常有用。

打字稿打字员

isNotNumber(value: string | number): value is string {
    return Number.isNaN(Number(this.smartImageWidth));
}
isNumber(value: string | number): value is number {
    return Number.isNaN(Number(this.smartImageWidth)) === false;
}

假设您的属性widthnumber | string number | string 。 您可能想根据是否为字符串来进行逻辑运算。

var width: number|string;
width = "100vw";

if (isNotNumber(width)) 
{
    // the compiler knows that width here must be a string
    if (width.endsWith('vw')) 
    {
        // we have a 'width' such as 100vw
    } 
}
else 
{
    // the compiler is smart and knows width here must be number
    var doubleWidth = width * 2;    
}

Typeguard足够聪明,可以将if语句中的width类型限制为ONLY string 。 这允许编译器允许width.endsWith(...) ,如果类型为string | number不允许string | number string | number

您可以将typeGuard命名为isNotNumberisNumberisStringisNotString但我认为isString有点模棱两可且难以阅读。


#21楼

我最近写了一篇有关确保变量为有效数字的方法的文章: https : //github.com/jehugaleahsa/artifacts/blob/master/2018/typescript_num_hack.md本文介绍了如何确保浮点数或整数(如果是)重要( +x vs ~~x )。

本文假定变量是一个stringnumber开头,并且trim可用/多填充。 同样,将其扩展为处理其他类型也不难。 这是它的实质:

// Check for a valid float
if (x == null
    || ("" + x).trim() === ""
    || isNaN(+x)) {
    return false;  // not a float
}

// Check for a valid integer
if (x == null
    || ("" + x).trim() === ""
    || ~~x !== +x) {
    return false;  // not an integer
}

#22楼

这个问题的公认答案有很多缺陷(其他几个用户都强调了这一点)。 这是在javascript中解决该问题的最简单且经过验证的方法之一:

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

以下是一些好的测试用例:

console.log(isNumeric(12345678912345678912)); // true
console.log(isNumeric('2 '));                 // true
console.log(isNumeric('-32.2 '));             // true
console.log(isNumeric(-32.2));                // true
console.log(isNumeric(undefined));            // false

// the accepted answer fails at these tests:
console.log(isNumeric(''));                   // false
console.log(isNumeric(null));                 // false
console.log(isNumeric([]));                   // false

#23楼

避免尝试查找“内置”解决方案的麻烦。

没有一个好的答案,并且在该线程中被高估的答案是错误的。

npm install is-number

在JavaScript中,可靠地检查值是否为数字并不总是那么简单。 开发人员通常使用+,-或Number()将字符串值转换为数字(例如,从用户输入,正则表达式匹配,解析器等返回值时)。 但是,有许多非直觉性的边缘案例会产生意想不到的结果:

console.log(+[]); //=> 0
console.log(+''); //=> 0
console.log(+'   '); //=> 0
console.log(typeof NaN); //=> 'number'

#24楼

function isNumberCandidate(s) {
  const str = (''+ s).trim();
  if (str.length === 0) return false;
  return !isNaN(+str);
}

console.log(isNumberCandidate('1'));       // true
console.log(isNumberCandidate('a'));       // false
console.log(isNumberCandidate('000'));     // true
console.log(isNumberCandidate('1a'));      // false 
console.log(isNumberCandidate('1e'));      // false
console.log(isNumberCandidate('1e-1'));    // true
console.log(isNumberCandidate('123.3'));   // true
console.log(isNumberCandidate(''));        // false
console.log(isNumberCandidate(' '));       // false
console.log(isNumberCandidate(1));         // true
console.log(isNumberCandidate(0));         // true
console.log(isNumberCandidate(NaN));       // false
console.log(isNumberCandidate(undefined)); // false
console.log(isNumberCandidate(null));      // false
console.log(isNumberCandidate(-1));        // true
console.log(isNumberCandidate('-1'));      // true
console.log(isNumberCandidate('-1.2'));    // true
console.log(isNumberCandidate(0.0000001)); // true
console.log(isNumberCandidate('0.0000001')); // true
console.log(isNumberCandidate(Infinity));    // true
console.log(isNumberCandidate(-Infinity));    // true

console.log(isNumberCandidate('Infinity'));  // true

if (isNumberCandidate(s)) {
  // use +s as a number
  +s ...
}

#25楼

只需使用isNaN() ,它将把字符串转换成一个数字 ,如果得到一个有效的数字 ,将返回false ...

isNaN("Alireza"); //return true
isNaN("123"); //return false

#26楼

我正在使用以下内容:

const isNumber = s => !isNaN(+s)

#27楼

使用纯JavaScript:

Number.isNaN(Number('1')); // false
Number.isNaN(Number('asdf')); // true

使用Lodash:

_.isNaN(_.toNumber('1')); // false
_.isNaN(_.toNumber('asdf')); // true

#28楼

对于TypeScript无效,因为:

declare function isNaN(number: number): boolean;

对于TypeScript,您可以使用:

/^\\d+$/.test(key)


#29楼

这是isNumber实现的高性能版本(2.5 * 10 ^ 7迭代/ s @ 3.8GHz Haswell)。 它适用于我可以找到的每个测试用例(包括符号):

var isNumber = (function () {
  var isIntegerTest = /^\d+$/;
  var isDigitArray = [!0, !0, !0, !0, !0, !0, !0, !0, !0, !0];
  function hasLeading0s (s) {
    return !(typeof s !== 'string' ||
    s.length < 2 ||
    s[0] !== '0' ||
    !isDigitArray[s[1]] ||
    isIntegerTest.test(s));
  }
  var isWhiteSpaceTest = /\s/;
  return function isNumber (s) {
    var t = typeof s;
    var n;
    if (t === 'number') {
      return (s <= 0) || (s > 0);
    } else if (t === 'string') {
      n = +s;
      return !((!(n <= 0) && !(n > 0)) || n === '0' || hasLeading0s(s) || !(n !== 0 || !(s === '' || isWhiteSpaceTest.test(s))));
    } else if (t === 'object') {
      return !(!(s instanceof Number) || ((n = +s), !(n <= 0) && !(n > 0)));
    }
    return false;
  };
})();

#30楼

2019年:包括ES3,ES6和TypeScript示例

也许这个问题已经被重复了很多次,但是我今天也与这个问题作斗争,并想发表我的答案,因为我没有看到任何其他答案能这么简单或彻底地做到这一点:

ES3

var isNumeric = function(num){
    return (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num);  
}

ES6

const isNumeric = (num) => (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num);

打字稿

const isNumeric = (num: any) => (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num as number);

这似乎很简单,涵盖了我在许多其他帖子上看到的所有基础,并自己思考:

// Positive Cases
console.log(0, isNumeric(0) === true);
console.log(1, isNumeric(1) === true);
console.log(1234567890, isNumeric(1234567890) === true);
console.log('1234567890', isNumeric('1234567890') === true);
console.log('0', isNumeric('0') === true);
console.log('1', isNumeric('1') === true);
console.log('1.1', isNumeric('1.1') === true);
console.log('-1', isNumeric('-1') === true);
console.log('-1.2354', isNumeric('-1.2354') === true);
console.log('-1234567890', isNumeric('-1234567890') === true);
console.log(-1, isNumeric(-1) === true);
console.log(-32.1, isNumeric(-32.1) === true);
console.log('0x1', isNumeric('0x1') === true);  // Valid number in hex
// Negative Cases
console.log(true, isNumeric(true) === false);
console.log(false, isNumeric(false) === false);
console.log('1..1', isNumeric('1..1') === false);
console.log('1,1', isNumeric('1,1') === false);
console.log('-32.1.12', isNumeric('-32.1.12') === false);
console.log('[blank]', isNumeric('') === false);
console.log('[spaces]', isNumeric('   ') === false);
console.log('null', isNumeric(null) === false);
console.log('undefined', isNumeric(undefined) === false);
console.log([], isNumeric([]) === false);
console.log('NaN', isNumeric(NaN) === false);

您也可以尝试使用自己的isNumeric函数,并在这些用例中isNumeric试,然后为所有用例扫描“ true”。

或者,查看每个返回的值:

针对<code> isNumeric()</ code>的每个测试的结果


#31楼

好吧,我正在使用我制作的这个...

到目前为止,它一直在工作:

function checkNumber(value) {
    if ( value % 1 == 0 )
    return true;
    else
    return false;
}

如果您发现任何问题,请告诉我。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值