ตรวจสอบว่าอักขระเป็นตัวเลขหรือไม่?


102

ฉันต้องการตรวจสอบว่า justPrices[i].substr(commapos+2,1)ฉันจำเป็นต้องตรวจสอบว่า

สตริงมีลักษณะดังนี้: "blabla, 120"

ในกรณีนี้จะตรวจสอบว่า '0' เป็นตัวเลขหรือไม่ จะทำได้อย่างไร?


1
อาจซ้ำกันได้ที่นี่
cctan

1
@cctan มันไม่ซ้ำกัน คำถามนั้นเกี่ยวกับการตรวจสอบสตริงซึ่งเกี่ยวกับการตรวจสอบอักขระ
jackocnr

คำตอบ:


68

คุณสามารถใช้ตัวดำเนินการเปรียบเทียบเพื่อดูว่าอยู่ในช่วงของอักขระหลักหรือไม่:

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 การทดสอบของคุณจะคืนค่าจริงสำหรับสตริงที่มีมากกว่าแค่อักขระ (เช่นis_numeric_char("foo1bar") == true) หากคุณต้องการตรวจสอบอักขระตัวเลข/^\d$/.test(c)จะเป็นทางออกที่ดีกว่า แต่อย่างไรก็ตามมันไม่ใช่คำถาม :)
Yaron U.

24

แก้ไข: คำตอบที่อัปเดตของ Blender เป็นคำตอบที่ถูกต้องที่นี่หากคุณกำลังตรวจสอบอักขระเดี่ยว (กล่าวคือ !isNaN(parseInt(c, 10)) ) คำตอบของฉันด้านล่างเป็นวิธีแก้ปัญหาที่ดีหากคุณต้องการทดสอบสตริงทั้งหมด

นี่คือisNumericการนำไปใช้งานของ jQuery (ใน JavaScript บริสุทธิ์) ซึ่งทำงานกับสตริงทั้งหมด :

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

ความคิดเห็นสำหรับฟังก์ชันนี้อ่านว่า:

// parseFloat NaNs ตัวเลขที่สร้างผลบวกเท็จ (null | true | false | "")
// ... แต่ตีความสตริงเลขนำหน้าผิดโดยเฉพาะเลขฐานสิบหก ("0x ... ")
// การลบบังคับให้ infinities ไปยัง NaN

ฉันคิดว่าเราสามารถวางใจได้ว่า chaps เหล่านี้ใช้เวลากับเรื่องนี้ไม่น้อย!

แหล่งที่มาแสดงความคิดเห็นที่นี่ อภิปราย geek ซูเปอร์ที่นี่


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

คุณสามารถปล่อยค่าพารามิเตอร์ 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 เป็นตัวเลขหรือไม่


4

ฉันขอแนะนำ regex ง่ายๆ

หากคุณกำลังมองหาเพียงอักขระสุดท้ายในสตริง:

/^.*?[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

และ regex นั้นง่ายกว่าถ้าคุณแค่ตรวจสอบ char เดียวเป็นอินพุต:

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;

หากคุณต้องการตรวจสอบมากกว่า 1 แชทเตอร์คุณอาจใช้ตัวแปรถัดไป

นิพจน์ทั่วไป:

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

ฉันใช้คล้ายกับหนึ่งในคำตอบข้างต้น

 var sum = 0; //some value
 let num = parseInt(val); //or just Number.parseInt
 if(!isNaN(num)) {
     sum += num;
 }

บล็อกโพสต์นี้ให้ความกระจ่างมากขึ้นในการตรวจสอบว่าสตริงเป็นตัวเลขใน Javascript | หรือไม่ typescript และ ES6


1

วิธีง่ายๆโดยใช้ประโยชน์จากการตรวจสอบประเภทไดนามิกของภาษา:

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

ดูกรณีทดสอบด้านล่าง


0

ดูเหมือนว่าจะได้ผล:

การผูกแบบคงที่:

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

การผูกต้นแบบ:

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

จะตรวจสอบอักขระเดี่ยวและสตริงทั้งหมดเพื่อดูว่าเป็นตัวเลขหรือไม่




0

คุณสามารถลองสิ่งนี้ (ใช้ได้ในกรณีของฉัน)

หากคุณต้องการทดสอบว่าอักขระตัวแรกของสตริงเป็น int หรือไม่:

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

หากคุณต้องการทดสอบว่าถ่านเป็น 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);

การคูณด้วยหนึ่งจะทำให้ได้ตัวเลขจากสตริงตัวเลขใด ๆ (เนื่องจากคุณมีอักขระเพียงตัวเดียวมันจะเป็นจำนวนเต็มตั้งแต่ 0 ถึง 9 เสมอ) และ a NaNสำหรับสตริงอื่น ๆ


โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.