Controlla se il carattere è un numero?


102

Devo controllare se justPrices[i].substr(commapos+2,1).

La stringa è qualcosa del tipo: "blabla, 120"

In questo caso controllerebbe se "0" è un numero. Come si può fare?


1
possibile duplicare qui
cctan

1
@cctan Non è un duplicato. Questa domanda riguarda il controllo di una stringa, si tratta di controllare un carattere.
jackocnr

Risposte:


68

È possibile utilizzare operatori di confronto per vedere se è compreso nell'intervallo di caratteri numerici:

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

1
Ho pensato anche a questo. Perché nessuno lo usa e fa invece confronti complicati? In alcuni casi non funzionerà?
user826955

43

puoi usare parseInte poi controllare conisNaN

o se vuoi lavorare direttamente sulla tua stringa puoi usare regexp in questo modo:

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

4
O anche più semplice se dobbiamo controllare un solo carattere:function is_numeric_char(c) { return /\d/.test(c); }
jackocnr

1
@jackocnr il tuo test restituirà anche true per le stringhe che contengono più di un semplice carattere (ad esempio is_numeric_char("foo1bar") == true). se vuoi controllare un carattere numerico /^\d$/.test(c)sarebbe una soluzione migliore. ma comunque, non era la domanda :)
Yaron U.

24

EDIT: la risposta aggiornata di Blender è la risposta giusta qui se stai solo controllando un singolo carattere (vale a dire !isNaN(parseInt(c, 10))). La mia risposta di seguito è una buona soluzione se vuoi testare intere stringhe.

Ecco l' isNumericimplementazione di jQuery (in puro JavaScript), che funziona con stringhe complete :

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

Il commento per questa funzione recita:

// parseFloat NaNs falsi positivi con cast numerico (null | true | false | "")
// ... ma interpreta male le stringhe dei numeri iniziali, in particolare i letterali esadecimali ("0x ...")
// la sottrazione forza gli infiniti a NaN

Penso che possiamo fidarci del fatto che questi ragazzi abbiano dedicato un bel po 'di tempo a questo!

Fonte commentata qui . Discussione super geek qui .


2
Funziona, ma è eccessivo per il controllo di sole cifre (funziona con numeri a più cifre). La mia soluzione potrebbe non essere così chiara, ma è molto più veloce di questa.
user2486570

18

Mi chiedo perché nessuno abbia pubblicato una soluzione come:

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

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

con un'invocazione come:

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

cercato esattamente quel tipo di soluzione - ty
Matthias Herrmann

È possibile eliminare il valore del parametro 0 per charCodeAt poiché 0 è implicito quando il parametro non è fornito.
Dave de Jong

16

Puoi usare questo:

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

Qui, l'ho confrontato con il metodo accettato: http://jsperf.com/isdigittest/5 . Non mi aspettavo molto, quindi sono rimasto piuttosto sorpreso quando ho scoperto che il metodo accettato era molto più lento.

La cosa interessante è che mentre il metodo accettato è un input corretto più veloce (es. "5") e più lento per errato (es. "A"), il mio metodo è esattamente opposto (veloce per errato e più lento per corretto).

Tuttavia, nel peggiore dei casi, il mio metodo è 2 volte più veloce della soluzione accettata per un input corretto e oltre 5 volte più veloce per un input errato.


5
Amo questa risposta! Forse ottimizzalo per: !!([!0, !0, !0, !0, !0, !0, !0, !0, !0, !0][n]);ha un grande potenziale WTF e funziona abbastanza bene (fallisce per 007).
Jonathan

@ Jonathan - vedi la mia risposta , metodo n. 4
vsync

7
Secondo questa 'soluzione', "length"(e altri attributi trovati sugli array) sono cifre: P
Shadow

12

Penso che sia molto divertente trovare modi per risolvere questo problema. Di seguito sono riportati alcuni.
(Tutte le funzioni seguenti presumono che l' argomento sia un singolo carattere. Modificare in n[0]per applicarlo)

Metodo 1:

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

Metodo 2:

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

Metodo 3:

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

Metodo 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
  }
})();

Metodo 5:

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

Stringa di prova:

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

Metodi 1, 2, 3 e 5 output trueper " ".
user247702

Per divertimento ho fatto un jsperf di questi, poi ho aggiunto un charCodeAt()confronto - che era quasi 4 volte più veloce - jsperf.com/isdigit3
Rycochet

@ Rycochet - buona. La gamma di codici ASCII è davvero il modo migliore per testare ..
vsync


5

Se stai testando singoli caratteri, allora:

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

restituirà vero o falso a seconda che c sia una cifra o meno.


4

Suggerisco una semplice regex.

Se stai cercando solo l'ultimo carattere nella stringa:

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

E la regex è ancora più semplice se stai solo controllando un singolo carattere come input:

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

4

La soluzione più breve è:

const isCharDigit = n => n < 10;

Puoi applicare anche questi:

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

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

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

se vuoi controllare più di 1 chatacter, potresti usare le varianti successive

Espressione regolare:

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

Confronto:

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

Controlla se non è 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));
    }
}

output senza modalità rigorosa:

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

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

true
true
false
false

output con modalità rigorosa:

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

Provare:

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

0

Questo sembra funzionare:

Legame statico:

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

Rilegatura prototipo:

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

Controllerà i singoli caratteri, così come intere stringhe per vedere se sono numerici.


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

fonte


0
function is_numeric(mixed_var) {
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') &&
        mixed_var !== '' && !isNaN(mixed_var);
}

Codice sorgente


0

Puoi provare questo (ha funzionato nel mio caso)

Se vuoi verificare se il primo carattere di una stringa è un int:

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

Se vuoi verificare se il carattere è un int:

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

0

Questa funzione funziona per tutti i casi di test che ho trovato. È anche più veloce di:

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)


Ho risolto il caso "0".
c7x43t

0

Per quanto ne so, il modo più semplice è moltiplicare per 1:

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

La moltiplicazione per uno crea un numero da qualsiasi stringa numerica (poiché hai un solo carattere, sarà sempre un numero intero da 0 a 9) e a NaNper qualsiasi altra stringa.



0

Una soluzione semplice sfruttando il controllo dinamico del tipo del linguaggio:

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

vedere i casi di test di seguito


-1

Basta usare isFinite

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

Ciò restituisce vero per uno spazio ""
Michael Bray
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.