如何检查一个数字是浮点数还是整数?

如何找出一个数字是floatinteger

1.25 --> float1 --> integer0 --> integer0.25 --> float
908908 次浏览

尝试这些函数来测试一个值是否是一个没有小数部分的数字基元值,并且在可以表示为精确整数的大小限制内。

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

正如其他人提到的,你在JS中只有双精度。那么如何定义一个数字是整数?只需检查舍入的数字是否等于它自己:

function isInteger(f) {return typeof(f)==="number" && Math.round(f) == f;}function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }

这真的取决于你想实现什么。如果你想“模仿”强类型语言,那么我建议你不要尝试。正如其他人提到的,所有数字都有相同的表示(相同的类型)。

使用类似于Claudiu提供的东西:

isInteger( 1.0 )->true

这看起来很符合常识,但在像C这样的东西中,你会得到false

除以1时检查余数:

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

如果你不知道参数是一个数字,你需要两个测试:

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

2019年更新这个答案写出5年后,ECMA Script 2015中标准化了一个解决方案。该解决方案涵盖在这个答案

以下是检查值是数字还是可以是安全地转换为数字的有效函数:

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

对于整数(如果值是浮点数,则返回false):

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

这里的效率是当值已经是一个数字时避免parseInt(或parseNumber)。两个解析函数总是首先转换为字符串,然后尝试解析该字符串,如果值已经是一个数字,这将是一种浪费。

感谢这里的其他帖子为优化提供进一步的想法!

这是检查INT和FLOAT的最终代码

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

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

对于整数,我使用这个

function integer_or_null(value) {if ((undefined === value) || (null === value)) {return null;}if(value % 1 != 0) {return null;}return value;}
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');}

为什么不是这样的:

var isInt = function(n) { return parseInt(n) === n };
parseInt(yourNumber)=== parseFloat(yourNumber)

另一种方法是:

    function isFloat(float) {return /\./.test(float.toString());}

可能不如其他方法有效,但另一种方法都是一样的。

您可以使用一个简单的正则表达式:

function isInt(value) {
var er = /^-?[0-9]+$/;
return er.test(value);}

或者您也可以根据需要使用以下功能。它们是由PHPJS项目开发的。

is_int()=>检查变量类型是否为整数,其内容是否为整数

is_float()=>检查变量类型是否为浮点数,其内容是否为浮点数

ctype_digit()=>检查变量类型是否为字符串,其内容是否只有十进制数字

更新1

现在它也检查负数,感谢@ChrisBartley评论

它真的不必那么复杂。整数的parseFloat()和parseInt()等价物的数值将是相同的。因此,您可以这样做:

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

然后

if (isInt(x)) // do work

这也将允许字符串检查,因此不严格。如果想要一个强类型解决方案(也就是,不适用于字符串):

function is_int(value){ return !isNaN(parseInt(value * 1) }
function isInt(n){return n != "" && !isNaN(n) && Math.round(n) == n;}function isFloat(n){return n != "" && !isNaN(n) && Math.round(n) != n;}

适用于所有情况。

在java脚本中,所有数字都是internally 64 bit floating point,与java中的双精度相同。javascript中没有不同的类型,所有类型都由类型number表示。因此,您将无法进行instanceof检查。但是,您可以使用上面给出的解决方案来确定它是否是小数。java脚本的设计者认为使用单一类型可以避免许多类型转换错误。

任何具有零小数部分的浮点数(例如1.0、12.00、0.0)都隐式转换为整数,因此无法检查它们是否为浮点数。

这是我对整数的使用:

Math.ceil(parseFloat(val)) === val

简短,漂亮:)一直有效。如果我没弄错的话,这就是大卫·弗拉纳根的建议。

!!(24%1) // false!!(24.2%1) // true
var isInt = function (n) { return n === (n | 0); };

还没有过这样做不起作用的案例。

有一个名为Number.isInteger()的方法,目前在除IE之外的所有浏览器中都实现了。MDN还为其他浏览器提供了一个Poly填充:

Number.isInteger = Number.isInteger || function(value) {return typeof value === 'number' &&isFinite(value) &&Math.floor(value) === value;};

但是,对于大多数用例,您最好使用Number.isSafeInteger,它还会检查值是否太高/太低,以至于任何小数位都会丢失。MDN也为此提供了一个多边形。(您还需要上面的isInteger pollyill。)

if (!Number.MAX_SAFE_INTEGER) {Number.MAX_SAFE_INTEGER = 9007199254740991; // Math.pow(2, 53) - 1;}Number.isSafeInteger = Number.isSafeInteger || function (value) {return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;};

简单整数测试:

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

有道理:如果JavaScript可以将某些东西转换为整数,并且通过转换它变成了完全相同的东西,那么您的操作数就是一个整数。

控制台的测试用例:

x = 1;     x===parseInt(x); // truex = "1";   x===parseInt(x); // falsex = 1.1;   x===parseInt(x); // false, obviously
// BUT!
x = 1.0;   x===parseInt(x); // true, because 1.0 is NOT a float!

这让很多人感到困惑。每当某个东西是.0时,它就不再是浮点数了。它是一个整数。或者你可以称它为“数字事物”,因为没有像C中那样严格的区别。美好的旧时光。

所以基本上,你所能做的就是检查整数,接受1.000是整数的事实。

有趣的旁注

有一个关于巨大数字的评论。巨大的数字对这种方法来说没有问题;每当parseInt无法处理数字(因为它太大)时,它将返回比实际值更多的东西,所以测试将返回FALSE。看:

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);

我在2014年在IE8上测试了这个,然后在2021年在Chrome上测试了这个,两者都返回“a是可以的;b失败”,这意味着如果一个数字太大,它就不能再是整数了。

20位数对任何人来说都足够了,引用经典。

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);        // trueisFloat(1.0);          // falseisFloat(1.2);          // trueisInteger(1.2);        // falseisFloat(1);            // falseisInteger(1);          // trueisFloat(2e+2);         // falseisInteger(2e+2);       // trueisFloat('1');          // falseisInteger('1');        // falseisFloat(NaN);          // falseisInteger(NaN);        // falseisFloat(null);         // falseisInteger(null);       // falseisFloat(undefined);    // falseisInteger(undefined);  // false

基于我在这里看到的所有内容,我创建了自己的一组函数来测试我需要的内容:

function NumberValidator() {this.isFloat = function (n) {return typeof(n)==="number" && n === +n && Math.round(n) !== n;};
this.isInteger = function (n) {return typeof(n)==="number" && n === +n && Math.round(n) === n;};
this.isFloatOrInteger = function (n) {return this.isFloat(n) || this.isInteger(n);};
this.isNonZeroFloatOrInteger = function (n) {return this.isFloatOrInteger(n) && n > 0;};
this.isNonZeroInteger = function (n) {return this.isInteger(n) && n > 0;};}

然而,shime的解决方案更短,检查更少,所以它可能是一个更好的解决方案。

这可能不像%答案那样高性能,它可以防止您首先转换为字符串,但我还没有看到有人发布它,所以这里有另一个应该可以正常工作的选项:

function isInteger(num) {return num.toString().indexOf('.') === -1;}

对于那些好奇的人,使用Benchmark.js我在这篇文章中测试了投票最多的答案(以及今天发布的答案),以下是我的结果:

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 Runsuite.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

这是我的:

function isInt(quale) {var valore = $('#'+quale).val().toLowerCase();if (isNaN(Number(String(valore))) || (valore.indexOf("e") > 0)) {// Not int} else {// Is Int!}}

还有这个:

function isFloat(quale) {var valore = $('#'+quale).val();valore = valore.replace(",", "");if (isNaN(String(valore)) || (valore.indexOf("e") > 0)) {// Not Float} else {// Float}}

大人物!

这是我的代码。它检查以确保它不是一个空字符串(否则会通过),然后将其转换为数字格式。现在,取决于您是否希望'1.1'等于1.1,这可能是也可能不是您要查找的。

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;
};

我喜欢这个小函数,它对正整数和负整数都返回true:

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

这是有效的,因为1或“1”变成了“1.0”,isNaN()返回false(然后我们否定并返回),但是1.0或“1.0”变成了“1.0.0”,而“string”变成了“string.0”,两者都不是数字,所以isNaN()返回false(并且再次被否定)。

如果你只想要正整数,有这个变体:

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

或者,对于负整数:

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

isPositiveInt()的工作原理是将连接的数字字符串移动到要测试的值之前。例如,isPositiveInt(1)导致isNaN()评估“01”,评估为false。同时,isPositiveInt(-1)导致isNaN()评估“0-1”,评估为true。我们否定返回值,这给了我们想要的。isNegativeInt()的工作原理类似,但不否定isNaN()的返回值。

编辑:

我最初的实现也会在数组和空字符串上返回true。这个实现没有那个缺陷。如果val不是字符串或数字,或者如果它是一个空字符串,它还可以提前返回,在这种情况下更快。您可以通过将前两个子句替换为

typeof(val) != "number"

如果您只想匹配文字数字(而不是字符串)

编辑:

我还不能发表评论,所以我将此添加到我的答案中。@Asok发布的基准测试信息非常丰富;但是,最快的函数不符合要求,因为它还为浮点数、数组、布尔值和空字符串返回TRUE。

我创建了以下测试套件来测试每个函数,并将我的答案添加到列表中(函数8解析字符串,函数9不解析字符串):

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!");}

我还重新运行了基准测试,并将函数#8添加到列表中。我不会发布结果,因为它们有点尴尬(例如,该函数不是很快)…

(删节-我删除了成功的测试,因为输出很长)结果如下:

Testing function 0Value: (object) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (boolean) true, Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (boolean) false, Expect: (boolean) false, Result: (boolean) true, Match: falseValue: null, Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/AValue: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/AValue: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/AFAIL!
Testing function 1Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/APASS!
Testing function 2Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/APASS!
Testing function 3Value: (object) true, Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (object) false, Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (boolean) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (boolean) [object Object], Expect: (boolean) false, Result: (boolean) true, Match: falseValue: null, Expect: (boolean) false, Test skipped; function threw exception!Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (string) 'a', Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/AValue: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/AValue: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/AFAIL!
Testing function 4Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/APASS!
Testing function 5Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/APASS!
Testing function 6Value: null, Expect: (boolean) false, Test skipped; function threw exception!Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/AValue: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/AValue: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/APASS!
Testing function 7Value: (number) 1.1, Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (number) -1.1, Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (object) true, Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (boolean) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (boolean) [object Object], Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: falseValue: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/AValue: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/AValue: (string) '1.1', Expect: (ANY), Result: (boolean) true, Match: N/AValue: (string) '-1.1', Expect: (ANY), Result: (boolean) true, Match: N/AFAIL!
Testing function 8Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/AValue: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/AValue: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/APASS!
Testing function 9Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/AValue: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/APASS!

我留下了失败,所以你可以看到每个函数失败的地方,(字符串)'#'测试,所以你可以看到每个函数如何处理字符串中的整数和浮点值,因为有些人可能希望这些被解析为数字,有些人可能不希望。

在测试的10个功能中,真正符合OP要求的是[1,3,5,6,8,9]

浮动验证的条件:

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

整数验证的条件:

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

希望这能有所帮助。

下面的函数可以防止空字符串、未定义、空值和最大/最小值范围。Javascript引擎应该从第一天起就内置了这些函数。:)

好好享受!

function IsInteger(iVal) {var iParsedVal; //our internal converted int value

iParsedVal = parseInt(iVal,10);
if (isNaN(iParsedVal) || Infinity == iParsedVal || -Infinity == iParsedVal) //sanity check - guard against empty strings and max/min valuesreturn false;elsereturn Number(iVal) === (iParsedVal | 0); //the 2nd operand group (intValue | 0), evaluates to true only if the intValue is an integer; so an int type will only return true}
function IsFloat(fVal) {var fParsedVal; //our internal converted float value

fParsedVal = parseFloat(fVal);
if (isNaN(fParsedVal) || Infinity == fParsedVal || -Infinity == fParsedVal) //sanity check - guard against empty strings and max/min valuesreturn false;elsereturn !!(fVal % 1); //true only if there is a fractional value after the mod op; the !! returns the opposite value of the op which reflects the function's return value}
function int(a) {return a - a === 0 && a.toString(32).indexOf('.') === -1}
function float(a) {return a - a === 0 && a.toString(32).indexOf('.') !== -1}

如果要排除字符串,可以添加typeof a === 'number'

YourJS提供了以下两个函数,适用于所有数字,包括为-InfinityInfinity返回false

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

由于typeOf()是YourJS内部函数,如果您想使用这些定义,您可以在此处下载这些函数的版本:http://yourjs.com/snippets/build/34

有时Number对象不允许您使用直接mod运算符(%),如果您面临这种情况,您可以使用此解决方案。

if(object instanceof Number ){if( ((Number) object).doubleValue() % 1 == 0 ){//your object is an integer}else{//your object is a double}}

我需要检查输入值是整数还是浮点数,为此我想出了以下方法:

function isInteger(x) {var integer = parseInt(x, 10);if (!isNaN(integer) && !isFloat(x)) {return true;}return false;}
function isFloat(x) {var f = parseFloat(x);var floor = Math.floor(f);var fraction = f - floor;if (fraction > 0) {return true;}return false;}
var cases = ["1","1.00","1.01","0.05","ab1","ab1.1",1,1.00,1.01,0.05,1e+5,"",true,false,null,NaN,undefined,];
console.log("isInteger()");for (var i = 0; i < cases.length; i++) {console.log(cases[i], isInteger(cases[i]));}
console.log("\nisFloat()");for (var i = 0; i < cases.length; i++) {console.log(cases[i], isFloat(cases[i]));}

我觉得这是最优雅的方式:

function isInteger(n) {return n === (n^0);}

它还关心在非数值的情况下返回false。

try this onefunction amountcheck(){var dpamt=$('#dpamt').val()/5000;var ints=dpamt.toString();var isint=ints.split('.');if(isint[1]>0){alert('float value');return false;}else{alert('int value');}}

在这里尝试了一些答案,我最终编写了这个解决方案。这也适用于字符串中的数字。

function isInt(number) {if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;return !(number - parseInt(number));}
function isFloat(number) {if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;return number - parseInt(number) ? true : false;}

    var tests = {'integer' : 1,'float' : 1.1,'integerInString' : '5','floatInString' : '5.5','negativeInt' : -345,'negativeFloat' : -34.98,'negativeIntString' : '-45','negativeFloatString' : '-23.09','notValidFalse' : false,'notValidTrue' : true,'notValidString' : '45lorem','notValidStringFloat' : '4.5lorem','notValidNan' : NaN,'notValidObj' : {},'notValidArr' : [1,2],};
function isInt(number) {if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;return !(number - parseInt(number));}    
function isFloat(number) {if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;return number - parseInt(number) ? true : false;}
function testFunctions(obj) {var keys = Object.keys(obj);var values = Object.values(obj);
values.forEach(function(element, index){console.log(`Is ${keys[index]} (${element}) var an integer? ${isInt(element)}`);console.log(`Is ${keys[index]} (${element}) var a float? ${isFloat(element)}`);});}
testFunctions(tests);

这个解决方案为我工作。

<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>

这个怎么样?

isFloat(num) {return typeof num === "number" && !Number.isInteger(num);}

试试这个

let n;return (n = value % 1) !== 0 && !isNaN(n);

当返回值为false时,表示输入值为浮点数或浮点字符串,否则输入值为整数numbef或整数字符串。

基本上它需要检查精度值是否不等于零。

另一个是检查正确的字符串编号。

我们可以通过isInteger函数进行检查。IE数字将返回true,浮点数返回false

console.log(Number.isInteger(2)),<BR>

将返回true

console.log(Number.isInteger(2.5))

将返回false

您可以使用Number.isInteger()方法通过除以它们来检查数字是整数还是浮点数,例如:

    function isNumberFloatOrInteger(a, b){if(Number.isInteger(a / b)){return true;}else{ return false };}

注意:isInteger()与Internet Explorer不兼容。

有Number.is整数(数字)来检查这个。在Internet Explorer中不起作用,但该浏览器不再使用。如果您需要像“90”这样的字符串作为整数(这不是问题),请尝试Number.is整数(数字(数字))。“官方”isInteger将9.0视为整数,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number。看起来大多数答案对于旧浏览器都是正确的,但现代浏览器已经继续前进,实际上支持浮点整数检查。

对于浮动

var decimal=  /^[-+]?[0-9]+\.[0-9]+$/;
if (!price.match(decimal)) {alert('Please enter valid float');return false;}

对于整数

var number = /^\d+$/;
if (!price.match(number)) {alert('Please enter valid integer');return false;}

有了这个,您可以检查字符串或数字是否为“十进制”(正确浮动):

var IsDecimal = function(num){return ((num.toString().split('.').length) <= 2 && num.toString().match(/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/)) ? (!isNaN(Number.parseFloat(num))) : false ;}

另一个用于检查字符串或数字是否为整数:

var IsInteger = function(num){return ((num.toString().split('.').length) == 1 && num.toString().match(/^[\-]?\d+$/)) ? (!isNaN(Number.parseInt(num))) : false ;}

var IsDecimal = function(num){return ((num.toString().split('.').length) <= 2 && num.toString().match(/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/)) ? (!isNaN(Number.parseFloat(num))) : false ;}
var IsInteger = function(num){return ((num.toString().split('.').length) == 1 && num.toString().match(/^[\-]?\d+$/)) ? (!isNaN(Number.parseInt(num))) : false ;}

console.log("-------------- As string --------------");console.log("Integers:");console.log("0 = " + IsInteger("0"));console.log("34 = " + IsInteger("34"));console.log(".34 = " + IsInteger(".34"));console.log("3.4 = " + IsInteger("3.4"));console.log("3e = " + IsInteger("3e"));console.log("e3 = " + IsInteger("e3"));console.log("-34 = " + IsInteger("-34"));console.log("--34 = " + IsInteger("--34"));console.log("034 = " + IsInteger("034"));console.log("0-34 = " + IsInteger("0-34"));console.log("Floats/decimals:");console.log("0 = " + IsDecimal("0"));console.log("64 = " + IsDecimal("64"));console.log(".64 = " + IsDecimal(".64"));console.log("6.4 = " + IsDecimal("6.4"));console.log("6e2 = " + IsDecimal("6e2"));console.log("6e = " + IsDecimal("6e"));console.log("e6 = " + IsDecimal("e6"));console.log("-64 = " + IsDecimal("-64"));console.log("--64 = " + IsDecimal("--64"));console.log("064 = " + IsDecimal("064"));console.log("0-64 = " + IsDecimal("0-64"));console.log("\n-------------- As numbers --------------");console.log("Integers:");console.log("0 = " + IsInteger(0));console.log("34 = " + IsInteger(34));console.log(".34 = " + IsInteger(0.34));console.log("3.4 = " + IsInteger(3.4));console.log("-34 = " + IsInteger(-34));console.log("034 = " + IsInteger(034));console.log("0-34 = " + IsInteger(0-34));console.log("Floats/decimals:");console.log("0 = " + IsDecimal(0));console.log("64 = " + IsDecimal(64));console.log(".64 = " + IsDecimal(0.64));console.log("6.4 = " + IsDecimal(6.4));console.log("6e2 = " + IsDecimal(6e2));console.log("-64 = " + IsDecimal(-64));console.log("064 = " + IsDecimal(064));console.log("0-64 = " + IsDecimal(0-64));

要检查数字是否为Int并应用2个十进制格式,您可以在React-Native中使用以下公式。

isInt = (n) => {return n % 1 === 0;}
show = (x) => {if(x) {if (this.isInt(x)) {return ${x}}else {return ${x.toFixed(2)}}}}

我知道已经有30个答案了,但一个复杂的方法是这样做:

function isInteger(n) {return n.toString().split('.').length === 1;}

解释:我们首先将n转换为字符串,并根据点对其进行拆分。如果n是浮点,就像4.5一样,那么拆分将返回一个数组['4', '5']。如果它是一个整数,就像45一样,它将返回['45']。因此,如果数组的长度为1,那么我们知道它是一个数字。

附注:如果您想以新的ES6格式(箭头函数)编写此函数:

const isInteger = n => n.toString().split('.').length === 1;

这是我能想到的最好的解决方案,用于浮点数和整数检查。

function isFloat(n) {if (!n) {return false}return !isNaN(n % 1) && n % 1 !== 0;}
function isInt(n) {if (n.length==0) {return false}return !isNaN(n % 1) && n % 1 == 0;}

const integerCheck = (num) => {const isInt = (n) => Number(n) === n && n % 1 === 0const isFloat = (n) => Number(n) === n && n % 1 !== 0return (isInt(num) || !isFloat(num))}console.log( integerCheck('23.3') );

2022更新-我们可以简单地使用数字的方法。

检查整数还是浮点数:Number.isFinite(val)

检查是否为整数:Number.isInteger(val)

检查是否为浮点数(不是整数):!Number.isInteger(val) && Number.isFinite(val)

我迟到了,但这是我的版本

isInteger: obj => Number.isInteger(!isNaN(obj % 1) && obj % 1 !== 0 ? obj : parseInt(obj)),