检查字符是否为数字?


101

我需要检查是否justPrices[i].substr(commapos+2,1)

该字符串类似于:“ blabla,120”

在这种情况下,它将检查“ 0”是否为数字。如何才能做到这一点?


1
可能重复到这里
cctan 2012年

1
@cctan不是重复的。这个问题是关于检查字符串,这是关于检查字符。
jackocnr

Answers:


67

您可以使用比较运算符查看它是否在数字字符范围内:

var c = justPrices[i].substr(commapos+2,1);
if (c >= '0' && c <= '9') {
    // it is a number
} else {
    // it isn't
}

1
我也想出了这个。为什么没有人使用它,而是进行复杂的比较?在某些情况下这会行不通吗?
user826955

43

你可以使用 parseIntisNaN

或者,如果您想直接处理字符串,则可以使用regexp,如下所示:

function is_numeric(str){
    return /^\d+$/.test(str);
}

4
如果我们只需要检查一个字符,甚至更简单:function is_numeric_char(c) { return /\d/.test(c); }
jackocnr

1
@jackocnr对于包含多个字符(例如is_numeric_char("foo1bar") == true)以外的字符串,测试也将返回true 。如果要检查数字字符,/^\d$/.test(c)将是更好的解决方案。但无论如何,这不是问题:)
Yaron U.

24

编辑:Blender的更新的答案是正确的答案在这里,如果您只是检查一个字符(即 !isNaN(parseInt(c, 10))),。如果您想测试整个字符串,下面的答案是一个很好的解决方案。

这是jQuery的isNumeric实现(使用纯JavaScript),适用于完整字符串

function isNumeric(s) {
    return !isNaN(s - parseFloat(s));
}

该函数的注释为:

// parseFloat NaNs数字转换误报(null | true | false |“”)
// ...但是误解了前导数字字符串,尤其是十六进制文字(“ 0x ...”)
//减去强制将无穷大化为NaN

我认为我们可以相信,这些小伙子为此花费了很多时间!

评论来源在这里。超级极客在这里讨论。


2
此方法有效,但是对于仅进行数字检查(它适用于多位数的数字)来说是一个过大的选择。我的解决方案可能不太清楚,但是比这快得多。
user2486570

18

我想知道为什么没人发布这样的解决方案:

var charCodeZero = "0".charCodeAt(0);
var charCodeNine = "9".charCodeAt(0);

function isDigitCode(n) {
   return(n >= charCodeZero && n <= charCodeNine);
}

调用类似:

if (isDigitCode(justPrices[i].charCodeAt(commapos+2))) {
    ... // digit
} else {
    ... // not a digit
}

正是在寻找这种解决方案-ty
Matthias Herrmann

您可以删除charCodeAt的0参数值,因为未提供参数时隐含0。
Dave de Jong

16

您可以使用此:

function isDigit(n) {
    return Boolean([true, true, true, true, true, true, true, true, true, true][n]);
}

在这里,我将其与公认的方法进行了比较:http : //jsperf.com/isdigittest/5。我没想到太多,所以当我发现公认的方法慢得多时,我感到非常惊讶。

有趣的是,虽然可接受的方法正确输入的速度较快(例如“ 5”),错误输入的速度较慢(例如“ a”),但我的方法却恰恰相反(错误的速度较快,正确的速度较慢)。

尽管如此,在最坏的情况下,我的方法比正确输入的公认解决方案快2倍,而对于错误输入则要超过5倍。


5
我喜欢这个答案!也许将其优化为:!!([!0, !0, !0, !0, !0, !0, !0, !0, !0, !0][n]);它具有巨大的WTF潜力,并且运作良好(失败007)。
乔纳森

@Jonathan-参见我的答案,方法4
vsync

7
根据此“解决方案”,"length"(以及在数组中找到的其他属性)是数字:P
Shadow

12

我认为想出办法解决这个问题非常有趣。以下是一些。
(下面的所有函数均假定参数为单个字符。更改为n[0]为强制执行)

方法1:

function isCharDigit(n){
  return !!n.trim() && n > -1;
}

方法2:

function isCharDigit(n){
  return !!n.trim() && n*0==0;
}

方法3:

function isCharDigit(n){
  return !!n.trim() && !!Number(n+.1); // "+.1' to make it work with "." and "0" Chars
}

方法4:

var isCharDigit = (function(){
  var a = [1,1,1,1,1,1,1,1,1,1];
  return function(n){
    return !!a[n] // check if `a` Array has anything in index 'n'. Cast result to boolean
  }
})();

方法5:

function isCharDigit(n){
  return !!n.trim() && !isNaN(+n);
}

测试字符串:

var str = ' 90ABcd#?:.+', char;
for( char of str ) 
  console.log( char, isCharDigit(char) );

方法1,2,3和5输出true" "
user247702

为了好玩,我做了一个jsperf,然后添加了一个charCodeAt()比较-快了将近4倍-jsperf.com/isdigit3
Rycochet

@Rycochet-很好。ASCII码的范围确实是测试的最好方式..
VSYNC


5

如果要测试单个字符,则:

var isDigit = (function() {
    var re = /^\d$/;
    return function(c) {
        return re.test(c);
    }
}());

将返回true或false,具体取决于c是否为数字。


4

我建议一个简单的正则表达式。

如果您只在寻找字符串中的最后一个字符:

/^.*?[0-9]$/.test("blabla,120");  // true
/^.*?[0-9]$/.test("blabla,120a"); // false
/^.*?[0-9]$/.test("120");         // true
/^.*?[0-9]$/.test(120);           // true
/^.*?[0-9]$/.test(undefined);     // false
/^.*?[0-9]$/.test(-1);            // true
/^.*?[0-9]$/.test("-1");          // true
/^.*?[0-9]$/.test(false);         // false
/^.*?[0-9]$/.test(true);          // false

如果只检查单个字符作为输入,则正则表达式甚至更简单:

var char = "0";
/^[0-9]$/.test(char);             // true

4

最短的解决方案是:

const isCharDigit = n => n < 10;

您也可以应用这些:

const isCharDigit = n => Boolean(++n);

const isCharDigit = n => '/' < n && n < ':';

const isCharDigit = n => !!++n;

如果要检查多个角色,则可以使用下一个变体

正则表达式:

const isDigit = n => /\d+/.test(n);

比较:

const isDigit = n => +n == n;

检查是否不是NaN

const isDigit = n => !isNaN(n);

3
var Is = {
    character: {
        number: (function() {
            // Only computed once
            var zero = "0".charCodeAt(0), nine = "9".charCodeAt(0);

            return function(c) {
                return (c = c.charCodeAt(0)) >= zero && c <= nine;
            }
        })()
    }
};

1
isNumber = function(obj, strict) {
    var strict = strict === true ? true : false;
    if (strict) {
        return !isNaN(obj) && obj instanceof Number ? true : false;
    } else {
        return !isNaN(obj - parseFloat(obj));
    }
}

没有严格模式的输出:

var num = 14;
var textnum = '14';
var text = 'yo';
var nan = NaN;

isNumber(num);
isNumber(textnum);
isNumber(text);
isNumber(nan);

true
true
false
false

以严格模式输出:

var num = 14;
var textnum = '14';
var text = 'yo';
var nan = NaN;

isNumber(num, true);
isNumber(textnum, true);
isNumber(text, true);
isNumber(nan);

true
false
false
false

1

尝试:

function is_numeric(str){
        try {
           return isFinite(str)
        }
        catch(err) {
            return false
        }
    }

0

这似乎可行:

静态绑定:

String.isNumeric = function (value) {
    return !isNaN(String(value) * 1);
};

原型绑定:

String.prototype.isNumeric = function () {
    return !isNaN(this.valueOf() * 1);
};

它将检查单个字符以及整个字符串以查看它们是否为数字。


0
square = function(a) {
    if ((a * 0) == 0) {
        return a*a;
    } else {
        return "Enter a valid number.";
    }
}

资源



0

您可以尝试一下(在我的情况下有效)

如果要测试字符串的第一个字符是否为int:

if (parseInt(YOUR_STRING.slice(0, 1))) {
    alert("first char is int")
} else {
    alert("first char is not int")
}

如果要测试char是否为int:

if (parseInt(YOUR_CHAR)) {
    alert("first char is int")
} else {
    alert("first char is not int")
}

0

此功能适用于我可以找到的所有测试用例。它也比:

function isNumeric (n) {
  if (!isNaN(parseFloat(n)) && isFinite(n) && !hasLeading0s(n)) {
    return true;
  }
  var _n = +n;
  return _n === Infinity || _n === -Infinity;
}

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/;

function fIsNaN(n) {
  return !(n <= 0) && !(n > 0);
}

function isNumber(s) {
  var t = typeof s;
  if (t === 'number') {
    return (s <= 0) || (s > 0);
  } else if (t === 'string') {
    var n = +s;
    return !(fIsNaN(n) || hasLeading0s(s) || !(n !== 0 || !(s === '' || isWhiteSpaceTest.test(s))));
  } else if (t === 'object') {
    return !(!(s instanceof Number) || fIsNaN(+s));
  }
  return false;
}

function testRunner(IsNumeric) {
  var total = 0;
  var passed = 0;
  var failedTests = [];

  function test(value, result) {
    total++;
    if (IsNumeric(value) === result) {
      passed++;
    } else {
      failedTests.push({
        value: value,
        expected: result
      });
    }
  }
  // true
  test(0, true);
  test(1, true);
  test(-1, true);
  test(Infinity, true);
  test('Infinity', true);
  test(-Infinity, true);
  test('-Infinity', true);
  test(1.1, true);
  test(-0.12e-34, true);
  test(8e5, true);
  test('1', true);
  test('0', true);
  test('-1', true);
  test('1.1', true);
  test('11.112', true);
  test('.1', true);
  test('.12e34', true);
  test('-.12e34', true);
  test('.12e-34', true);
  test('-.12e-34', true);
  test('8e5', true);
  test('0x89f', true);
  test('00', true);
  test('01', true);
  test('10', true);
  test('0e1', true);
  test('0e01', true);
  test('.0', true);
  test('0.', true);
  test('.0e1', true);
  test('0.e1', true);
  test('0.e00', true);
  test('0xf', true);
  test('0Xf', true);
  test(Date.now(), true);
  test(new Number(0), true);
  test(new Number(1e3), true);
  test(new Number(0.1234), true);
  test(new Number(Infinity), true);
  test(new Number(-Infinity), true);
  // false
  test('', false);
  test(' ', false);
  test(false, false);
  test('false', false);
  test(true, false);
  test('true', false);
  test('99,999', false);
  test('#abcdef', false);
  test('1.2.3', false);
  test('blah', false);
  test('\t\t', false);
  test('\n\r', false);
  test('\r', false);
  test(NaN, false);
  test('NaN', false);
  test(null, false);
  test('null', false);
  test(new Date(), false);
  test({}, false);
  test([], false);
  test(new Int8Array(), false);
  test(new Uint8Array(), false);
  test(new Uint8ClampedArray(), false);
  test(new Int16Array(), false);
  test(new Uint16Array(), false);
  test(new Int32Array(), false);
  test(new Uint32Array(), false);
  test(new BigInt64Array(), false);
  test(new BigUint64Array(), false);
  test(new Float32Array(), false);
  test(new Float64Array(), false);
  test('.e0', false);
  test('.', false);
  test('00e1', false);
  test('01e1', false);
  test('00.0', false);
  test('01.05', false);
  test('00x0', false);
  test(new Number(NaN), false);
  test(new Number('abc'), false);
  console.log('Passed ' + passed + ' of ' + total + ' tests.');
  if (failedTests.length > 0) console.log({
    failedTests: failedTests
  });
}
testRunner(isNumber)


我修复了'0'的情况。
c7x43t

0

据我所知,最简单的方法是乘以1

var character = ... ; // your character
var isDigit = ! isNaN(character * 1);

乘以1可以从任何数字字符串中得到一个数字(因为您只有一个字符,它将始终是0到9之间的整数),而NaN其他任何字符串都可以得到a 。



0

利用语言的动态类型检查的简单解决方案:

function isNumber (string) {
   //it has whitespace
   if(string === ' '.repeat(string.length)){
     return false
   }
   return string - 0 === string * 1
}

请参阅下面的测试用例


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.