IsNumeric()
함수와 동일한 개념적 공간에 무언가가 있기를 바랍니다.
질문자 :Electrons_Ahoy
2020년 10월 2일: 많은 기본 접근 방식에는 여기에 있는 많은 답변에서 고려하지 못하는 미묘한 버그(예: 공백, 암시적 부분 구문 분석, 기수, 배열 강제 변환 등)가 있습니다. 다음 구현이 적합할 수 있지만 소수점 " .
" 이외의 숫자 구분 기호는 지원하지 않습니다.
function isNumeric(str) { if (typeof str != "string") return false // we only process strings! return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)... !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail }
변수(문자열 포함)가 숫자인지 확인하려면 숫자가 아닌지 확인합니다.
이것은 변수 내용이 문자열이든 숫자이든 상관없이 작동합니다.
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 isNaN('') // false isNaN(' ') // false isNaN(false) // false
물론 필요한 경우 이를 무효화할 수 있습니다. 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
(이름에서 알 수 있듯이)는 소수점 이하의 모든 것을 잘라서 float를 정수로 변환합니다(이 동작 때문에 parseInt()
를 사용하려는 경우 아마도 더 나을 것입니다. 대신 다른 방법을 사용하여 해제 ):
+'12.345' // 12.345 parseInt(12.345) // 12 parseInt('12.345') // 12
빈 문자열
빈 문자열은 다소 직관적이지 않을 수 있습니다. +num
빈 문자열이나 공백이 있는 문자열을 0으로 변환하고 isNaN()
은 동일하다고 가정합니다.
+'' // 0 +' ' // 0 isNaN('') // false isNaN(' ') // false
그러나 parseInt()
는 동의하지 않습니다.
parseInt('') // NaN parseInt(' ') // NaN
Dan
문자열이 정수인지(소수점 없음) 확인하려는 경우 정규식을 사용하는 것이 좋습니다. isNaN
과 같은 다른 방법은 너무 단순한 것에 비해 너무 복잡합니다.
function isNumeric(value) { return /^-?\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(1234n)); // 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
Gavin
그리고 RegExp 방식으로 갈 수 있습니다.
var num = "987238"; if(num.match(/^-?\d+$/)){ //valid integer (positive or negative) }else if(num.match(/^\d+\.\d+$/)){ //valid float }else{ //not valid number }
roenving
이 질문에 대해 허용된 답변에는 몇 가지 결함이 있습니다(몇 명의 다른 사용자가 강조한 대로). 이것은 자바스크립트에서 접근하는 가장 쉽고 입증된 방법 중 하나입니다.
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
Hamzeen Hameem
문자열에 숫자, 임의의 숫자(정수 또는 부동 소수점), 정확히 숫자만 포함되도록 하려면 parseInt()
/ parseFloat()
, Number()
또는 !isNaN()
을 사용할 수 없습니다. 그들 자신. !isNaN()
은 실제로 Number()
가 숫자를 반환할 때 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가 인식할 때 부동 소수점 숫자를 일치시키기 위한 정확한 정규식을 생성하지 않으면 케이스를 놓치거나 인식해서는 안 되는 케이스를 인식하게 된다는 것입니다. 그리고 자신만의 정규식을 만들 수 있다고 해도 그 이유는 무엇입니까? 더 간단한 내장 방법이 있습니다.
그러나 Number()
(및 isNaN()
parseFloat()
가 숫자를 반환하지 않아야 할 때 반환하는 모든 경우에 대해 올바른 작업을 수행하며 그 반대의 경우도 마찬가지입니다. 따라서 문자열이 정말 정확하고 숫자일 뿐인지 알아보려면 두 함수를 모두 호출하고 둘 다 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)) }
Michael
isNan 기능을 사용해보십시오.
isNaN() 함수는 값이 잘못된 숫자인지(Not-a-Number) 확인합니다.
이 함수는 값이 NaN과 같으면 true를 반환합니다. 그렇지 않으면 false를 반환합니다.
이 함수는 Number 특정 Number.isNaN() 메서드와 다릅니다.
전역 isNaN() 함수는 테스트된 값을 숫자로 변환한 다음 테스트합니다.
Number.isNan()은 값을 숫자로 변환하지 않으며 숫자 유형이 아닌 값에 대해 true를 반환하지 않습니다...
theraccoonbear
오래된 질문이지만 주어진 답변에 몇 가지 요점이 누락되어 있습니다.
과학적 표기법.
!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자리로 제한하는 것이 좋습니다(앞에 0을 생략한 후).
무한대
> 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); }
그러나 이것조차도 완전한 것은 아닙니다. 선행 0은 여기에서 처리되지 않지만 길이 테스트를 망칩니다.
mark
나는 테스트했으며 Michael의 솔루션이 가장 좋습니다. 위의 답변에 투표하십시오("문자열을 찾으려면 이 페이지를 검색하세요"). 본질적으로 그의 대답은 다음과 같습니다.
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, [](및 기타?)
JohnP2
생성자에 인수를 전달할 때 Number 의 결과를 사용할 수 있습니다.
인수(문자열)를 숫자로 변환할 수 없는 경우 NaN을 반환하므로 제공된 문자열이 유효한 숫자인지 확인할 수 있습니다.
참고: 빈 문자열 또는 '\t\t'
및 '\n\t'
를 Number로 전달할 때 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
GibboK
아마도 평소보다 훨씬 더 엄격한 확인이 필요한(저처럼) 이 질문을 접하는 한두 사람이 있을 것입니다. 이 경우 다음이 유용할 수 있습니다.
if(str === String(Number(str))) { // it's a "perfectly formatted" number }
조심해! .1
, 40.000
, 080
, 00.1
과 같은 문자열을 거부합니다. 매우 까다롭습니다. 이 테스트를 통과 하려면 문자열이 숫자의 "가장 최소의 완벽한 형식 "과 일치해야 합니다.
String
및 Number
생성자를 사용하여 문자열을 숫자로 변환하고 다시 되돌리기 때문에 JavaScript 엔진의 "완벽한 최소 형식"(초기 Number
생성자로 변환된 형식)이 원래 문자열과 일치하는지 확인합니다.
user993683
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
함수를 시도하고 모든 항목에 대해 "true"를 검색할 수 있습니다.
또는 각각이 반환하는 값을 보려면 다음을 수행합니다.
Jeremy
jQuery의 구현이 충분하지 않은 이유는 무엇입니까?
function isNumeric(a) { var b = a && a.toString(); return !$.isArray(a) && b - parseFloat(b) + 1 >= 0; };
Michael은 다음과 같이 제안했습니다(여기서 "user1691651 - John"의 변경된 버전을 훔쳤지만).
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)); };
나는 현재 곤경에 처하게 될 몇 가지 사용 사례를 수동으로 테스트하는 것 외에 다른 방법으로 이러한 것들을 많이 테스트하지 않았습니다. 이는 모두 매우 표준적인 것입니다. 이것은 "거인의 어깨에 서있는"상황입니다.
Ultroman the Tacoman
2019: 실용적이고 엄격한 수치 유효성 검사
종종 '유효한 숫자'는 NaN과 Infinity를 제외한 자바스크립트 숫자, 즉 '유한 숫자'를 의미합니다.
값의 수치적 유효성을 확인하려면(예: 외부 소스에서) ESlint Airbnb 스타일에서 다음을 정의할 수 있습니다.
/** * Returns true if 'candidate' is a finite number or a string referring (not just 'including') a finite number * To keep in mind: * Number(true) = 1 * Number('') = 0 * Number(" 10 ") = 10 * !isNaN(true) = true * parseFloat('10 a') = 10 * * @param {?} candidate * @return {boolean} */ function isReferringFiniteNumber(candidate) { if (typeof (candidate) === 'number') return Number.isFinite(candidate); if (typeof (candidate) === 'string') { return (candidate.trim() !== '') && Number.isFinite(Number(candidate)); } return false; }
다음과 같이 사용하십시오.
if (isReferringFiniteNumber(theirValue)) { myCheckedValue = Number(theirValue); } else { console.warn('The provided value doesn\'t refer to a finite number'); }
J.P. Duvet
TypeScript에는 다음과 같이 유효하지 않습니다.
declare function isNaN(number: number): boolean;
TypeScript의 경우 다음을 사용할 수 있습니다.
/^\d+$/.test(key)
Greg Wozniak
parseInt(), 그러나 이 함수는 예를 들어 parseInt("100px")에 대해 100을 반환한다는 점에서 약간 다릅니다.
liggett78
인용하다:
isNaN(num) // 변수에 유효한 숫자가 없으면 true를 반환합니다.
선행/후행 공백을 확인해야 하는 경우 완전히 사실이 아닙니다. 예를 들어 특정 숫자의 숫자가 필요하고 예를 들어 PIN에 대해 '111' 또는 '111'이 아닌 '1111'을 가져와야 하는 경우 입력.
더 나은 사용:
var num = /^\d+$/.test(num)
Siubear
null
에 대해 보호할 때
// Base cases that are handled properly Number.isNaN(Number('1')); // => false Number.isNaN(Number('-1')); // => false Number.isNaN(Number('1.1')); // => false Number.isNaN(Number('-1.1')); // => false Number.isNaN(Number('asdf')); // => true Number.isNaN(Number(undefined)); // => true // Special notation cases that are handled properly Number.isNaN(Number('1e1')); // => false Number.isNaN(Number('1e-1')); // => false Number.isNaN(Number('-1e1')); // => false Number.isNaN(Number('-1e-1')); // => false Number.isNaN(Number('0b1')); // => false Number.isNaN(Number('0o1')); // => false Number.isNaN(Number('0xa')); // => false // Edge cases that will FAIL if not guarded against Number.isNaN(Number('')); // => false Number.isNaN(Number(' ')); // => false Number.isNaN(Number(null)); // => false // Edge cases that are debatable Number.isNaN(Number('-0b1')); // => true Number.isNaN(Number('-0o1')); // => true Number.isNaN(Number('-0xa')); // => true Number.isNaN(Number('Infinity')); // => false Number.isNaN(Number('INFINITY')); // => true Number.isNaN(Number('-Infinity')); // => false Number.isNaN(Number('-INFINITY')); // => true
null
에 대해 보호하지 않는 경우
parseInt
사용:
// Base cases that are handled properly Number.isNaN(parseInt('1')); // => false Number.isNaN(parseInt('-1')); // => false Number.isNaN(parseInt('1.1')); // => false Number.isNaN(parseInt('-1.1')); // => false Number.isNaN(parseInt('asdf')); // => true Number.isNaN(parseInt(undefined)); // => true Number.isNaN(parseInt('')); // => true Number.isNaN(parseInt(' ')); // => true Number.isNaN(parseInt(null)); // => true // Special notation cases that are handled properly Number.isNaN(parseInt('1e1')); // => false Number.isNaN(parseInt('1e-1')); // => false Number.isNaN(parseInt('-1e1')); // => false Number.isNaN(parseInt('-1e-1')); // => false Number.isNaN(parseInt('0b1')); // => false Number.isNaN(parseInt('0o1')); // => false Number.isNaN(parseInt('0xa')); // => false // Edge cases that are debatable Number.isNaN(parseInt('-0b1')); // => false Number.isNaN(parseInt('-0o1')); // => false Number.isNaN(parseInt('-0xa')); // => false Number.isNaN(parseInt('Infinity')); // => true Number.isNaN(parseInt('INFINITY')); // => true Number.isNaN(parseInt('-Infinity')); // => true Number.isNaN(parseInt('-INFINITY')); // => true
parseFloat
사용:
// Base cases that are handled properly Number.isNaN(parseFloat('1')); // => false Number.isNaN(parseFloat('-1')); // => false Number.isNaN(parseFloat('1.1')); // => false Number.isNaN(parseFloat('-1.1')); // => false Number.isNaN(parseFloat('asdf')); // => true Number.isNaN(parseFloat(undefined)); // => true Number.isNaN(parseFloat('')); // => true Number.isNaN(parseFloat(' ')); // => true Number.isNaN(parseFloat(null)); // => true // Special notation cases that are handled properly Number.isNaN(parseFloat('1e1')); // => false Number.isNaN(parseFloat('1e-1')); // => false Number.isNaN(parseFloat('-1e1')); // => false Number.isNaN(parseFloat('-1e-1')); // => false Number.isNaN(parseFloat('0b1')); // => false Number.isNaN(parseFloat('0o1')); // => false Number.isNaN(parseFloat('0xa')); // => false // Edge cases that are debatable Number.isNaN(parseFloat('-0b1')); // => false Number.isNaN(parseFloat('-0o1')); // => false Number.isNaN(parseFloat('-0xa')); // => false Number.isNaN(parseFloat('Infinity')); // => false Number.isNaN(parseFloat('INFINITY')); // => true Number.isNaN(parseFloat('-Infinity')); // => false Number.isNaN(parseFloat('-INFINITY')); // => true
노트:
- 원래 질문을 처리하기 위해 문자열, 비어 있고 초기화되지 않은 값만 고려됩니다. 배열과 객체가 고려되는 값인 경우 추가적인 예외 사례가 존재합니다.
- 2진수, 8진수, 16진수 및 지수 표기법의 문자는 대소문자를 구분하지 않습니다(예: '0xFF', '0XFF', '0xfF' 등은 위에 표시된 테스트 사례에서 모두 동일한 결과를 산출함).
- 경우에 따라
Infinity
(대소문자 구분)Number
및Math
개체의 상수가 위의 메서드 중 하나로 결정되면 숫자가 아닌 것으로 결정됩니다. -
Number
로 변환되는 방법과 null 및 빈 문자열에null
경우가 존재하는 이유에 대한 설명은 여기 를 참조하십시오.
Abtin Gramian
누군가 이 정도까지 내려간다면 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
모든 제안을 환영합니다. :]
The Dembinski
최근에 변수가 유효한 숫자인지 확인하는 방법에 대한 기사를 작성했습니다. https://github.com/jehugaleahsa/artifacts/blob/master/2018/typescript_num_hack.md 이 기사에서는 부동 소수점 또는 정수를 보장하는 방법을 설명합니다. 중요합니다( +x
대 ~~x
).
이 기사에서는 변수가 string
또는 number
로 시작하고 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 }
Travis Parks
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 ... }
gvlax
제가 만든거 사용중인데...
지금까지 작동했습니다.
function checkNumber(value) { return value % 1 == 0; }
문제가 있으면 알려주세요.
Rafael
JS에서 숫자 확인:
숫자인지 확인하는 가장 좋은 방법:
isFinite(20) //True
문자열에서 값을 읽습니다. CSS *:
parseInt('2.5rem') //2 parseFloat('2.5rem') //2.5
정수의 경우:
isInteger(23 / 0) //False
값이 NaN인 경우:
isNaN(20) //False
vitoboski
TL;DR
그것은 크게 당신이 숫자로 해석하려는 작업에 따라 달라집니다.
내장 함수 비교
기존 소스 중 어느 것도 내 영혼을 만족시키지 못했기 때문에 이러한 기능에서 실제로 무슨 일이 일어나고 있는지 알아 내려고 노력했습니다.
이 질문에 대한 세 가지 즉각적인 대답은 다음과 같이 느껴졌습니다.
-
!isNaN(input)
+input === +input
과 동일한 출력을 제공함) -
!isNaN(parseFloat(input))
-
isFinite(input)
그러나 모든 시나리오에서 올바른 것이 있습니까?
여러 경우에 이러한 기능을 테스트하고 출력을 마크다운으로 생성했습니다. 다음과 같이 보입니다.
input | !isNaN(input) 또는+input===+input | !isNaN( parseFloat( input)) | isFinite( input) | 논평 |
---|---|---|---|---|
123 | - | |||
'123' | - | |||
12.3 | - | |||
'12.3' | - | |||
' 12.3 ' | 예상대로 빈 공백이 잘립니다. | |||
1_000_000 | 숫자 구분 기호도 이해해야 합니다. | |||
'1_000_000' | 놀라다! JS는 문자열 내부의 숫자 구분 기호를 구문 분석하지 않습니다. 자세한 내용은 이 문제를 확인하십시오. (그런 다음 float로 구문 분석이 작동하는 이유는 무엇입니까? 글쎄, 그렇지 않았습니다. ) | |||
'0b11111111' | 이진 형식은 당연히 이해해야 합니다. | |||
'0o377' | 8진수 형식도 이해합니다. | |||
'0xFF' | 물론 16진법은 이해됩니다. 다른 생각을 한 사람이 있습니까? | |||
'' | 빈 문자열은 숫자여야 합니까? | |||
' ' | 공백만 있는 문자열은 숫자여야 합니까? | |||
'알파벳' | 숫자가 아니라 모두가 동의합니다. | |||
'12.34Ab!@#$' | 아! parseFloat() 가 하는 일을 이해할 수 있습니다. 나에게 인상적이지는 않지만 특정 경우에 유용할 수 있습니다. | |||
'10e100' | 10 100 은 정말 숫자입니다. 하지만 주의! 최대 안전 정수 값 2 53 (약 9×10 15 )보다 훨씬 큽니다. 자세한 내용은 이것을 읽으십시오. | |||
'10e1000' | 나와 함께 말해, 도와줘! 비록 그것이 보일 수 있는 것처럼 미친 것은 아니지만. JavaScript에서 ~10 308 보다 큰 값은 무한대로 반올림됩니다. 자세한 내용은 여기 를 참조하세요. 그리고 예, isNaN() 은 무한대를 숫자로 간주하고 parseFloat() 는 무한대를 무한대로 구문 분석합니다. | |||
없는 | 이제 이것은 어색합니다. JS에서는 변환이 필요할 때 null이 0이 되고 유한한 숫자를 얻습니다. 그렇다면 parseFloat(null) NaN 반환해야 하는 이유는 무엇입니까? 누가 이 디자인 컨셉을 설명해주세요. | |||
찾으시는 주소가 없습니다 | 예상대로. | |||
무한대 | 앞에서 설명한 것처럼 isNaN() 은 무한대를 숫자로 간주하고 parseFloat() 는 무한대를 무한대로 구문 분석합니다. |
그래서 ... 그들 중 "정확한"것은 무엇입니까?
지금쯤이면 분명해야 하며, 이는 우리가 필요로 하는 것에 크게 달려 있습니다 . 예를 들어, null 입력을 0으로 간주할 수 있습니다. 이 경우 isFinite()
가 제대로 작동합니다.
다시 말하지만, 유효한 숫자로 간주되기 위해 10 10000000000 isNaN()
에서 약간의 도움을 받을 수 있습니다(문제는 여전히 남아 있지만-왜 그럴 것이며 어떻게 처리할 것인가)!
물론 시나리오를 수동으로 제외할 수 있습니다.
내 경우와 마찬가지로 null 케이스, 빈 문자열 케이스 및 공백 전용 문자열 케이스를 제외하고 isFinite()
의 출력이 정확히 필요했습니다. 또한 나는 정말로 거대한 숫자에 대해 두통이 없었습니다. 그래서 내 코드는 다음과 같았습니다.
/** * My necessity was met by the following code. */ if (input === null) { // Null input } else if (input.trim() === '') { // Empty or whitespace-only string } else if (isFinite(input)) { // Input is a number } else { // Not a number }
또한 이것은 테이블을 생성하는 JavaScript였습니다.
/** * Note: JavaScript does not print numeric separator inside a number. * In that single case, the markdown output was manually corrected. * Also, the comments were manually added later, of course. */ let inputs = [ 123, '123', 12.3, '12.3', ' 12.3 ', 1_000_000, '1_000_000', '0b11111111', '0o377', '0xFF', '', ' ', 'abc', '12.34Ab!@#$', '10e100', '10e1000', null, undefined, Infinity]; let markdownOutput = `| \`input\` | \`!isNaN(input)\` or <br>\`+input === +input\` | \`!isNaN(parseFloat(input))\` | \`isFinite(input)\` | Comment | | :---: | :---: | :---: | :---: | :--- |\n`; for (let input of inputs) { let outputs = []; outputs.push(!isNaN(input)); outputs.push(!isNaN(parseFloat(input))); outputs.push(isFinite(input)); if (typeof input === 'string') { // Output with quotations console.log(`'${input}'`); markdownOutput += `| '${input}'`; } else { // Output without quotes console.log(input); markdownOutput += `| ${input}`; } for (let output of outputs) { console.log('\t' + output); if (output === true) { markdownOutput += ` | <div style="color:limegreen">true</div>`; // markdownOutput += ` | `; // for stackoverflow } else { markdownOutput += ` | <div style="color:orangered">false</div>`; // markdownOutput += ` | `; // for stackoverflow } } markdownOutput += ` ||\n`; } // Replace two or more whitespaces with $nbsp; markdownOutput = markdownOutput.replaceAll(` `, ` `); // Print markdown to console console.log(markdownOutput);
Hasan Nahiyan Nobel
PFB 작업 솔루션:
function(check){ check = check + ""; var isNumber = check.trim().length>0? !isNaN(check):false; return isNumber; }
Predhin
"내장된" 솔루션을 찾는 수고를 덜 수 있습니다.
좋은 대답은 없으며 이 스레드에서 크게 찬성된 대답은 잘못되었습니다.
npm install is-number
JavaScript에서 값이 숫자인지 확실하게 확인하는 것이 항상 간단하지는 않습니다. 개발자가 +, - 또는 Number()를 사용하여 문자열 값을 숫자로 변환하는 것이 일반적입니다(예: 사용자 입력, 정규식 일치, 파서 등에서 값이 반환되는 경우). 그러나 예상치 못한 결과를 초래하는 비직관적인 엣지 케이스가 많이 있습니다.
console.log(+[]); //=> 0 console.log(+''); //=> 0 console.log(+' '); //=> 0 console.log(typeof NaN); //=> 'number'
cdeutsch
이것은 이전 답변과 의견 중 일부를 기반으로 합니다. 다음은 모든 극단적인 경우를 다루며 상당히 간결합니다.
const isNumRegEx = /^-?(\d*\.)?\d+$/; function isNumeric(n, allowScientificNotation = false) { return allowScientificNotation ? !Number.isNaN(parseFloat(n)) && Number.isFinite(n) : isNumRegEx.test(n); }
Zoman
이것은 겉보기에 무한한 수의 극단적 인 경우를 포착하는 것으로 보입니다.
function isNumber(x, noStr) { /* - Returns true if x is either a finite number type or a string containing only a number - If empty string supplied, fall back to explicit false - Pass true for noStr to return false when typeof x is "string", off by default isNumber(); // false isNumber([]); // false isNumber([1]); // false isNumber([1,2]); // false isNumber(''); // false isNumber(null); // false isNumber({}); // false isNumber(true); // false isNumber('true'); // false isNumber('false'); // false isNumber('123asdf'); // false isNumber('123.asdf'); // false isNumber(undefined); // false isNumber(Number.POSITIVE_INFINITY); // false isNumber(Number.NEGATIVE_INFINITY); // false isNumber('Infinity'); // false isNumber('-Infinity'); // false isNumber(Number.NaN); // false isNumber(new Date('December 17, 1995 03:24:00')); // false isNumber(0); // true isNumber('0'); // true isNumber(123); // true isNumber(123.456); // true isNumber(-123.456); // true isNumber(-.123456); // true isNumber('123'); // true isNumber('123.456'); // true isNumber('.123'); // true isNumber(.123); // true isNumber(Number.MAX_SAFE_INTEGER); // true isNumber(Number.MAX_VALUE); // true isNumber(Number.MIN_VALUE); // true isNumber(new Number(123)); // true */ return ( (typeof x === 'number' || x instanceof Number || (!noStr && x && typeof x === 'string' && !isNaN(x))) && isFinite(x) ) || false; };
dsmith63
따라서 처리하려는 테스트 케이스에 따라 다릅니다.
function isNumeric(number) { return !isNaN(parseFloat(number)) && !isNaN(+number); }
내가 찾고 있던 것은 자바 스크립트의 일반 유형의 숫자였습니다. 0, 1 , -1, 1.1 , -1.1 , 1E1 , -1E1 , 1e1 , -1e1, 0.1e10, -0.1.e10 , 0xAF1 , 0o172, Math.PI, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY
또한 문자열로 표현됩니다.
'0', '1', '-1', '1.1', '-1.1', '1E1', '-1E1', '1e1', '-1e1', '0.1e10', '-0.1.e10', '0xAF1', '0o172'
'', ' ', [], {}, null, undefined, NaN
으로 표시하지 않고 생략하고 싶었습니다.
오늘 현재 다른 모든 답변은 이러한 테스트 사례 중 하나에 실패한 것으로 보입니다.
lebobbi
약간 혼란스러운 내 시도, 아마도 최선의 해결책은 아닙니다.
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
Endless
이 함수를 폼 유효성 검사 도구로 사용했는데 사용자가 지수 함수를 작성할 수 없도록 하고 싶어서 이 함수를 생각해 냈습니다.
<script> function isNumber(value, acceptScientificNotation) { if(true !== acceptScientificNotation){ return /^-{0,1}\d+(\.\d+)?$/.test(value); } if (true === Array.isArray(value)) { return false; } return !isNaN(parseInt(value, 10)); } console.log(isNumber("")); // false console.log(isNumber(false)); // false console.log(isNumber(true)); // false console.log(isNumber("0")); // true console.log(isNumber("0.1")); // true console.log(isNumber("12")); // true console.log(isNumber("-12")); // true console.log(isNumber(-45)); // true console.log(isNumber({jo: "pi"})); // false console.log(isNumber([])); // false console.log(isNumber([78, 79])); // false console.log(isNumber(NaN)); // false console.log(isNumber(Infinity)); // false console.log(isNumber(undefined)); // false console.log(isNumber("0,1")); // false console.log(isNumber("1e-1")); // false console.log(isNumber("1e-1", true)); // true </script>
ling
출처 : http:www.stackoverflow.com/questions/175739/built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number
'etc. > StackOverFlow' 카테고리의 다른 글
다른 스레드에서 GUI를 어떻게 업데이트합니까? (0) | 2022.02.24 |
---|---|
UNION과 UNION ALL의 차이점은 무엇입니까? (0) | 2022.02.19 |
매개변수를 사용하는 Bash 별칭을 만드시겠습니까? (0) | 2022.02.19 |
Memcached 대 Redis? [닫은] (0) | 2022.02.19 |
JavaScript 정규식에서 일치하는 그룹에 어떻게 액세스합니까? (0) | 2022.02.19 |