문자가 숫자인지 확인 하시겠습니까?


101

나는 justPrices[i].substr(commapos+2,1).

문자열은 다음과 같습니다. "blabla, 120"

이 경우 '0'이 숫자인지 확인합니다. 어떻게 할 수 있습니까?


1
가능한 중복 여기
cctan

1
@cctan 중복이 아닙니다. 그 질문은 문자열 검사에 관한 것이고, 이것은 문자 검사에 관한 것입니다.
jackocnr

답변:


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

당신은 사용 parseInt하고 확인하는 것보다isNaN

또는 문자열에서 직접 작업하려면 다음과 같이 regexp를 사용할 수 있습니다.

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

4
또는 단일 문자 만 확인하면 더 간단합니다.function is_numeric_char(c) { return /\d/.test(c); }
jackocnr

1
@jackocnr 테스트는 문자 (예 :) 이상을 포함하는 문자열에 대해서도 true를 반환합니다 is_numeric_char("foo1bar") == true. 숫자 문자를 확인하려면 /^\d$/.test(c)더 나은 솔루션이 될 것입니다. 어쨌든, 그것은 질문 : 아니 었
Yaron U.

24

편집 : 블렌더의 업데이트 된 답변은 단일 문자 (즉 !isNaN(parseInt(c, 10)))를 확인하는 경우 여기에서 정답 입니다. 아래 내 대답은 전체 문자열을 테스트하려는 경우 좋은 솔루션입니다.

다음은 전체 문자열isNumeric 에 대해 작동하는 jQuery의 구현 (순수 JavaScript)입니다 .

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

이 함수에 대한 주석은 다음과 같습니다.

// parseFloat NaNs numeric-cast false positives (null | true | false | "")
// ... 그러나 선행 숫자 문자열, 특히 16 진수 리터럴 ( "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
}

타이 - 솔루션의 종류에 대해 정확히 검색
마티아스 헤르만

매개 변수가 제공되지 않으면 0이 내포되므로 charCodeAt의 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);
    }
}());

c가 숫자인지 아닌지에 따라 true 또는 false를 반환합니다.


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;

하나 이상의 chatacter를 확인하려면 다음 변형을 사용할 수 있습니다.

정규식 :

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
}

아래 테스트 사례 참조


-1

그냥 사용 isFinite

const number = "1";
if (isFinite(number)) {
    // do something
}

공백 ""에 대해 true를 반환합니다.
Michael Bray
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.