Jak sprawdzić, czy liczba jest zmiennoprzecinkowa lub całkowita?

Jak znaleźć liczbę float lub integer?

1.25 --> float  
1 --> integer  
0 --> integer  
0.25 --> float
Author: Sinister Beard, 2010-10-08

30 answers

Sprawdź, czy pozostała część jest dzielona przez 1:

function isInt(n) {
   return n % 1 === 0;
}

Jeśli nie wiesz, że argument jest liczbą, potrzebujesz dwóch testów:

function isInt(n){
    return Number(n) === n && n % 1 === 0;
}

function isFloat(n){
    return Number(n) === n && n % 1 !== 0;
}
 1085
Author: kennebec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-08 15:12:54

Wypróbuj te funkcje, aby sprawdzić, czy wartość jest liczbą pierwotną, która nie ma części ułamkowej i mieści się w granicach wielkości tego, co można przedstawić jako dokładną liczbę całkowitą.

function isFloat(n) {
    return n === +n && n !== (n|0);
}

function isInteger(n) {
    return n === +n && n === (n|0);
}
 142
Author: Dagg Nabbit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-23 23:58:23

Dlaczego nie coś takiego:

var isInt = function(n) { return parseInt(n) === n };
 81
Author: warfares,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-28 18:55:17

Istnieje metoda o nazwie Number.isInteger(), która jest obecnie zaimplementowana tylko w najnowszym Firefoksie i nadal jest częścią propozycji EcmaScript 6. Jednak MDN zapewnia polyfill dla innych przeglądarek, który odpowiada podanej w ECMA harmony:

if (!Number.isInteger) {
  Number.isInteger = function isInteger (nVal) {
    return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
  };
}
 50
Author: paperstreet7,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-08 06:12:04

Możesz użyć prostego wyrażenia regularnego:

function isInt(value) {

    var er = /^-?[0-9]+$/;

    return er.test(value);
}

Lub możesz również użyć poniższych funkcji, zgodnie z własnymi potrzebami. Są one rozwijane przez Phpjs Project .

is_int() => sprawdź, czy typ zmiennej jest liczbą całkowitą i czy jej zawartość jest liczbą całkowitą

is_float() => sprawdź, czy zmienna jest typu float i czy jej zawartość jest typu float

ctype_digit() => sprawdź, czy zmienna jest typu string i czy jej zawartość ma tylko cyfry dziesiętne

Aktualizacja 1

Teraz sprawdza też liczby ujemne, dzięki za @ChrisBartley komentarz !

 33
Author: Marcio Mazzucato,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:35

Oto efektywne funkcje, które sprawdzają, czy wartość jest liczbą, czy może być bezpiecznie przekonwertowana na liczbę:

function isNumber(value) {
    if ((undefined === value) || (null === value)) {
        return false;
    }
    if (typeof value == 'number') {
        return true;
    }
    return !isNaN(value - 0);
}

I dla liczb całkowitych (zwróci false, jeśli wartość jest zmiennoprzecinkowa):

function isInteger(value) {
    if ((undefined === value) || (null === value)) {
        return false;
    }
    return value % 1 == 0;
}

Wydajność polega na tym, że parseInt (lub parseNumber) są unikane, gdy wartość jest już liczbą. Obie funkcje parsujące Zawsze konwertują najpierw na łańcuch znaków, a następnie próbują go przetworzyć, co byłoby stratą, jeśli wartość już jest numer.

Dziękuję innym postom tutaj za dostarczenie dalszych pomysłów na optymalizację!

 17
Author: Tal Liron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-17 21:42:58
function isInteger(x) { return typeof x === "number" && isFinite(x) && Math.floor(x) === x; }
function isFloat(x) { return !!(x % 1); }

// give it a spin

isInteger(1.0);        // true
isFloat(1.0);          // false
isFloat(1.2);          // true
isInteger(1.2);        // false
isFloat(1);            // false
isInteger(1);          // true    
isFloat(2e+2);         // false
isInteger(2e+2);       // true
isFloat('1');          // false
isInteger('1');        // false
isFloat(NaN);          // false
isInteger(NaN);        // false
isFloat(null);         // false
isInteger(null);       // false
isFloat(undefined);    // false
isInteger(undefined);  // false
 11
Author: shime,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-24 14:44:45
function isInt(n) 
{
    return n != "" && !isNaN(n) && Math.round(n) == n;
}
function isFloat(n){
    return n != "" && !isNaN(n) && Math.round(n) != n;
}
Działa we wszystkich przypadkach.
 9
Author: Deepak Yadav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-12 13:03:22

Jak inni wspominali, masz tylko sobowtóry w JS. Jak więc zdefiniować liczbę całkowitą? Wystarczy sprawdzić czy liczba zaokrąglona jest równa sobie:

function isInteger(f) {
    return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }
 6
Author: Claudiu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-07 21:08:27

Oto, czego używam dla liczb całkowitych:

Math.ceil(parseFloat(val)) === val
Krótkie, ładne :) działa cały czas. To sugeruje David Flanagan, jeśli się nie mylę.
 6
Author: Arman McHitarian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-20 17:01:29

Dowolna liczba zmiennoprzecinkowa z zerową częścią dziesiętną (np. 1.0, 12.00, 0.0) jest domyślnie oddana do liczby całkowitej, więc nie można sprawdzić, czy są zmiennoprzecinkowe, czy nie.

 5
Author: Mike Mancini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-07 13:33:55
!!(24%1) // false
!!(24.2%1) // true
 4
Author: Виктор Дакалов,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-15 17:34:34
var isInt = function (n) { return n === (n | 0); };
Nie miałem sprawy, w której to nie zadziałało.
 4
Author: ankr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-08 16:01:02

To naprawdę zależy od tego, co chcesz osiągnąć. Jeśli chcesz" naśladować " mocno wpisane języki, to proponuję nie próbować. Jak inni wspominali, wszystkie liczby mają tę samą reprezentację (ten sam typ).

Używając czegoś w rodzaju Claudiu pod warunkiem:

isInteger( 1.0 ) -> true

Co wygląda dobrze dla zdrowego rozsądku, ale w czymś takim jak C dostałbyś false

 3
Author: galambalazs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-07 21:35:29

To proste jak:

if( n === parseInt(n) ) ...

Spróbuj tego w konsoli:

x=1;
x===parseInt(x); // true
x="1";
x===parseInt(x); // false
x=1.1;
x===parseInt(x); // false, obviously

// BUT!

x=1.0;
x===parseInt(x); // true, because 1.0 is NOT a float!
To myli wielu ludzi. Kiedy coś jest .0, to już nie pływak. To liczba całkowita. Albo można to po prostu nazwać "rzeczą liczbową", ponieważ nie ma ścisłego rozróżnienia jak wtedy w C. stare dobre czasy.

Więc zasadniczo, wszystko, co możesz zrobić, to sprawdzić liczbę całkowitą akceptując fakt, że 1.000 jest liczbą całkowitą.

Ciekawa strona

Był komentarz o wielkim liczby. Ogromne liczby nie oznaczają żadnego problemu dla tego podejścia; gdy parseInt nie jest w stanie obsłużyć liczby (ponieważ jest zbyt duża) zwróci coś innego niż rzeczywista wartość, więc test zwróci FALSE. Jest to dobra rzecz, ponieważ jeśli uznasz coś za "liczbę", zwykle oczekujesz, że JS będzie w stanie z nią obliczyć - więc tak, liczby są ograniczone i parseInt weźmie to pod uwagę , mówiąc to w ten sposób.

Spróbuj tego:

<script>

var a = 99999999999999999999;
var b = 999999999999999999999; // just one more 9 will kill the show!
var aIsInteger = (a===parseInt(a))?"a is ok":"a fails";
var bIsInteger = (b===parseInt(b))?"b is ok":"b fails";
alert(aIsInteger+"; "+bIsInteger);

</script>

W mojej przeglądarce (IE8) to zwraca "A jest ok; b nie", co jest dokładnie ze względu na ogromną liczbę w b. limit może się różnić, ale myślę, że 20 cyfr "powinno wystarczyć dla każdego", cytując klasyczny:) {]}

 3
Author: dkellner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-26 15:10:32

JEST TO OSTATECZNY KOD DO SPRAWDZENIA ZARÓWNO INT JAK I FLOAT

function isInt(n) { 
   if(typeof n == 'number' && Math.Round(n) % 1 == 0) {
       return true;
   } else {
       return false;
   }
} 

Lub

function isInt(n) {   
   return typeof n == 'number' && Math.Round(n) % 1 == 0;   
}   
 2
Author: Ken Le,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-22 20:54:18
function isInteger(n) {
   return ((typeof n==='number')&&(n%1===0));
}

function isFloat(n) {
   return ((typeof n==='number')&&(n%1!==0));
}

function isNumber(n) {
   return (typeof n==='number');
}
 2
Author: Vitim.us,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-12 23:29:07

Napisałem funkcję, która akceptuje ciągi znaków (jeśli ktoś będzie potrzebował)

function isInt(x) {
    return !isNaN(x) && eval(x).toString().length == parseInt(eval(x)).toString().length
}

function isFloat(x) {
    return !isNaN(x) && !isInt(eval(x)) && x.toString().length > 0
}

Przykład ouptuts:

console.log(isFloat('0.2'))  // true
console.log(isFloat(0.2))    // true
console.log(isFloat('.2'))   // true
console.log(isFloat('-.2'))  // true
console.log(isFloat(-'.2'))  // true
console.log(isFloat(-.2))    // true
console.log(isFloat('u.2'))  // false
console.log(isFloat('2'))    // false
console.log(isFloat('0.2u')) // false

console.log(isInt('187'))  // true
console.log(isInt(187))    // true
console.log(isInt('1.2'))  // false
console.log(isInt('-2'))   // true
console.log(isInt(-'1'))   // true
console.log(isInt('10e1')) // true
console.log(isInt(10e1))   // true
 2
Author: Dariusz Majchrzak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-23 14:23:42

Dla liczb całkowitych używam tego

function integer_or_null(value) {
    if ((undefined === value) || (null === value)) {
        return null;
    }
    if(value % 1 != 0) {
        return null;
    }
    return value;
}
 1
Author: neoneye,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-04 09:33:53

To naprawdę nie musi być takie skomplikowane. Wartość liczbowa równoważników parseFloat() i parseInt() integer będzie taka sama. W ten sposób możesz zrobić tak:

function isInt(value){ 
    return (parseFloat(value) == parseInt(value)) && !isNaN(value);
}

Then

if (isInt(x)) // do work

Pozwoli to również na sprawdzanie ciągów znaków, a zatem nie jest ścisłe. Jeśli chcesz mieć silne rozwiązanie typu (aka, nie będzie pracować z ciągami):

function is_int(value){ return !isNaN(parseInt(value * 1) }
 1
Author: SpYk3HH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-19 00:35:17

W java script wszystkie liczby są internally 64 bit floating point, takie same jak podwójne w Javie. W javascript nie ma różnych typów, wszystkie są reprezentowane przez typ number. Dlatego Nie będę mógł wykonać instanceof czeku. Jednak można użyć powyższych rozwiązań, aby dowiedzieć się, czy jest to liczba ułamkowa. projektanci java script czuli, że z jednym typem mogą uniknąć licznych błędów typu cast.

 1
Author: Punith Raj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-14 11:56:19

To może nie jest tak wydajne jak % answer, co zapobiega konieczności konwersji na ciąg znaków, ale nie widziałem jeszcze nikogo, aby go opublikować, więc oto kolejna opcja, która powinna działać dobrze:

function isInteger(num) {
    return num.toString().indexOf('.') === -1;
}
 1
Author: Axle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-03 18:55:11

Dla ciekawskich, za pomocą Benchmark.js testowałem najczęściej głosowane odpowiedzi (i te opublikowane dzisiaj) na ten post, oto moje wyniki:

var n = -10.4375892034758293405790;
var suite = new Benchmark.Suite;
suite
    // kennebec
    .add('0', function() {
        return n % 1 == 0;
    })
    // kennebec
    .add('1', function() {
        return typeof n === 'number' && n % 1 == 0;
    })
    // kennebec
    .add('2', function() {
        return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
    })

    // Axle
    .add('3', function() {
        return n.toString().indexOf('.') === -1;
    })

    // Dagg Nabbit
    .add('4', function() {
        return n === +n && n === (n|0);
    })

    // warfares
    .add('5', function() {
        return parseInt(n) === n;
    })

    // Marcio Simao
    .add('6', function() {
        return /^-?[0-9]+$/.test(n.toString());
    })

    // Tal Liron
    .add('7', function() {
        if ((undefined === n) || (null === n)) {
            return false;
        }
        if (typeof n == 'number') {
            return true;
        }
        return !isNaN(n - 0);
    });

// Define logs and Run
suite.on('cycle', function(event) {
    console.log(String(event.target));
}).on('complete', function() {
    console.log('Fastest is ' + this.filter('fastest').pluck('name'));
}).run({ 'async': true });

0 x 12,832,357 ops/sec ±0.65% (90 runs sampled)
1 x 12,916,439 ops/sec ±0.62% (95 runs sampled)
2 x 2,776,583 ops/sec ±0.93% (92 runs sampled)
3 x 10,345,379 ops/sec ±0.49% (97 runs sampled)
4 x 53,766,106 ops/sec ±0.66% (93 runs sampled)
5 x 26,514,109 ops/sec ±2.72% (93 runs sampled)
6 x 10,146,270 ops/sec ±2.54% (90 runs sampled)
7 x 60,353,419 ops/sec ±0.35% (97 runs sampled)

Fastest is 7 Tal Liron
 1
Author: jnthnjns,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-03 21:23:10

Oto Mój kod. Sprawdza, czy nie jest to pusty ciąg znaków (który w przeciwnym razie przejdzie), a następnie konwertuje go do formatu liczbowego. Teraz, w zależności od tego, czy chcesz, aby '1.1' był równy 1.1, może to być to, czego szukasz.

var isFloat = function(n) {
    n = n.length > 0 ? Number(n) : false;
    return (n === parseFloat(n));
};
var isInteger = function(n) {
    n = n.length > 0 ? Number(n) : false;
    return (n === parseInt(n));
};

var isNumeric = function(n){

   if(isInteger(n) || isFloat(n)){
        return true;
   }
   return false;

};
 1
Author: Michael Ryan Soileau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-30 16:00:07

Podoba mi się ta mała funkcja, która zwróci true zarówno dla dodatnich, jak i ujemnych liczb całkowitych:

function isInt(val) {
    return ["string","number"].indexOf(typeof(val)) > -1 && val !== '' && !isNaN(val+".0");
}

To działa, ponieważ 1 lub " 1 " staje się "1.0", które isNaN() zwraca false na (które następnie negujemy i zwracamy), ale 1.0 lub" 1.0 "staje się" 1.0.0", podczas gdy" string "staje się" string.0", z których żadna nie jest liczbami, więc isnan () zwraca false (i ponownie zostaje zanegowana).

Jeśli chcesz tylko dodatnich liczb całkowitych, istnieje taki wariant:

function isPositiveInt(val) {
    return ["string","number"].indexOf(typeof(val)) > -1 && val !== '' && !isNaN("0"+val);
}

Lub, dla negatywnego liczba całkowita:

function isNegativeInt(val) {
    return `["string","number"].indexOf(typeof(val)) > -1` && val !== '' && isNaN("0"+val);
}

IsPositiveInt () działa poprzez przesunięcie skonkatenowanego ciągu liczbowego przed testowaną wartością. Na przykład isPositiveInt(1) powoduje, że isNaN() ocenia wartość "01", która oblicza false. Tymczasem isPositiveInt (-1) powoduje, że isNaN() ocenia wartość "0-1", która ocenia wartość true. Negujemy wartość zwrotu i to daje nam to, czego chcemy. isnegativeint () działa podobnie, ale bez negowania wartości zwracanej przez isnan ().

Edit:

Moja oryginalna implementacja zwraca również true na tablicach i pustych łańcuchach. Ta implementacja nie ma tej wady. Ma również tę zaletę, że zwraca wcześniej, jeśli val nie jest ciągiem znaków lub liczbą, lub jeśli jest pustym ciągiem, co przyspiesza w takich przypadkach. Można go dalej modyfikować, zastępując dwie pierwsze klauzule

typeof(val) != "number"

Jeśli chcesz dopasować tylko liczby literalne (a nie ciągi)

Edit:

Nie mogę jeszcze dodawać komentarzy, więc dodaję to do mojej odpowiedzi. Benchmark posted by @ Asok jest bardzo pouczająca; jednak najszybsza funkcja nie spełnia wymagań, ponieważ zwraca również TRUE dla pływaków, tablic, booleanów i pustych łańcuchów.

Stworzyłem następujący zestaw testów, aby przetestować każdą z funkcji, dodając moją odpowiedź do listy, jak również (funkcja 8, która parsuje łańcuchy, i funkcja 9, która nie):

funcs = [
    function(n) {
        return n % 1 == 0;
    },
    function(n) {
        return typeof n === 'number' && n % 1 == 0;
    },
    function(n) {
        return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
    },
    function(n) {
        return n.toString().indexOf('.') === -1;
    },
    function(n) {
        return n === +n && n === (n|0);
    },
    function(n) {
        return parseInt(n) === n;
    },
    function(n) {
        return /^-?[0-9]+$/.test(n.toString());
    },
    function(n) {
        if ((undefined === n) || (null === n)) {
            return false;
        }
        if (typeof n == 'number') {
            return true;
        }
        return !isNaN(n - 0);
    },
    function(n) {
        return ["string","number"].indexOf(typeof(n)) > -1 && n !== '' && !isNaN(n+".0");
    }
];
vals = [
    [1,true],
    [-1,true],
    [1.1,false],
    [-1.1,false],
    [[],false],
    [{},false],
    [true,false],
    [false,false],
    [null,false],
    ["",false],
    ["a",false],
    ["1",null],
    ["-1",null],
    ["1.1",null],
    ["-1.1",null]
];

for (var i in funcs) {
    var pass = true;
    console.log("Testing function "+i);
    for (var ii in vals) {
        var n = vals[ii][0];
        var ns;
        if (n === null) {
            ns = n+"";
        } else {
            switch (typeof(n)) {
                case "string":
                    ns = "'" + n + "'";
                    break;
                case "object":
                    ns = Object.prototype.toString.call(n);
                    break;
                default:
                    ns = n;
            }
            ns = "("+typeof(n)+") "+ns;
        }

        var x = vals[ii][1];
        var xs;
        if (x === null) {
            xs = "(ANY)";
        } else {
            switch (typeof(x)) {
                case "string":
                    xs = "'" + n + "'";
                    break;
                case "object":
                    xs = Object.prototype.toString.call(x);
                    break;
                default:
                    xs = x;
            }
            xs = "("+typeof(x)+") "+xs;
        }

        var rms;
        try {
            var r = funcs[i](n);
            var rs;
            if (r === null) {
                rs = r+"";
            } else {
                switch (typeof(r)) {
                    case "string":
                        rs = "'" + r + "'";
                        break;
                    case "object":
                        rs = Object.prototype.toString.call(r);
                        break;
                    default:
                        rs = r;
                }
                rs = "("+typeof(r)+") "+rs;
            }

            var m;
            var ms;
            if (x === null) {
                m = true;
                ms = "N/A";
            } else if (typeof(x) == 'object') {
                m = (xs === rs);
                ms = m;
            } else {
                m = (x === r);
                ms = m;
            }
            if (!m) {
                pass = false;
            }
            rms = "Result: "+rs+", Match: "+ms;
        } catch (e) {
            rms = "Test skipped; function threw exception!"
        }

        console.log("    Value: "+ns+", Expect: "+xs+", "+rms);
    }
    console.log(pass ? "PASS!" : "FAIL!");
}

Przeskanowałem również benchmark z funkcją # 8 dodaną do listy. Nie będę zamieszczał wyników, bo są trochę żenujące (np. Ta funkcja jest Nie szybko)...

(skrócone -- usunąłem udane testy, ponieważ wyjście jest dość długie) wyniki są następujące:

Testing function 0
Value: (object) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) false, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: null, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
FAIL!

Testing function 1
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 2
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 3
Value: (object) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (object) false, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Object], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: null, Expect: (boolean) false, Test skipped; function threw exception!
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) 'a', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
FAIL!

Testing function 4
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 5
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 6
Value: null, Expect: (boolean) false, Test skipped; function threw exception!
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 7
Value: (number) 1.1, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (number) -1.1, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (object) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Object], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) true, Match: N/A
FAIL!

Testing function 8
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 9
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Zostawiłem w awariach, więc możesz zobaczyć, gdzie każda funkcja zawodzi, a (string) ' # ' testuje, więc możesz zobaczyć, jak każda funkcja obsługuje wartości integer I float w łańcuchach, ponieważ niektóre mogą chcieć, aby były przetwarzane jako liczby, a niektóre nie.

Spośród 10 testowanych funkcji, te, które faktycznie spełniają wymagania OP to [1,3,5,6,8,9]

 1
Author: KeMBro2012,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-08 17:58:32

Condition for floating validation:

if (lnk.value == +lnk.value && lnk.value != (lnk.value | 0)) 

Condition for Integer validation:

if (lnk.value == +lnk.value && lnk.value == (lnk.value | 0)) 
Mam nadzieję, że to może być pomocne.
 1
Author: Joe Mike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-13 11:03:13
function int(a) {
  return a - a === 0 && a.toString(32).indexOf('.') === -1
}

function float(a) {
  return a - a === 0 && a.toString(32).indexOf('.') !== -1
}

Możesz dodać typeof a === 'number', jeśli chcesz wykluczyć ciągi.

 1
Author: Mirek Rusin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-24 01:02:06

YourJS zapewnia następujące dwie funkcje, które działają dla wszystkich liczb, w tym zwracając false dla -Infinity i Infinity:

function isFloat(x) {
  return typeOf(x, 'Number') && !!(x % 1);
}

function isInt(x) {
  return typeOf(x, 'Number') && x % 1 == 0;
}

Ze względu na fakt, że typeOf() jest wewnętrzną funkcją YourJS, jeśli chcesz użyć tych definicji, możesz pobrać wersję dla tych funkcji tutaj: http://yourjs.com/snippets/build/34

 1
Author: Chris West,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-25 11:57:44

Czasami liczba obiektów nie pozwala na użycie bezpośredniego operatora mod ( % ), jeśli masz do czynienia z takim przypadkiem, możesz użyć tego rozwiązania.

if(object instanceof Number ){
   if( ((Number) object).doubleValue() % 1 == 0 ){
      //your object is an integer
   }
   else{
      //your object is a double
   }
}
 1
Author: toddsalpen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-02 21:35:26

To rozwiązanie zadziałało dla mnie.

<html>
<body>
  <form method="post" action="#">
    <input type="text" id="number_id"/>
    <input type="submit" value="send"/>
  </form>
  <p id="message"></p>
  <script>
    var flt=document.getElementById("number_id").value;
    if(isNaN(flt)==false && Number.isInteger(flt)==false)
    {
     document.getElementById("message").innerHTML="the number_id is a float ";
    }
   else 
   {
     document.getElementById("message").innerHTML="the number_id is a Integer";
   }
  </script>
</body>
</html>
 1
Author: Abdelraouf GR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-29 11:57:31