[英]How do I check that a number is float or integer?
如何找到一个数字是float
还是integer
?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
除以 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;
}
在编写此答案 5 年后更新 2019 ,在 ECMA Script 2015 中标准化了一个解决方案。该解决方案包含在此答案中。
尝试使用这些函数来测试一个值是否是一个没有小数部分并且在可以表示为精确整数的大小限制内的数字原始值。
function isFloat(n) {
return n === +n && n !== (n|0);
}
function isInteger(n) {
return n === +n && n === (n|0);
}
有一个名为Number.isInteger()
的方法,目前在除 IE 之外的所有应用程序中都实现了该方法。 MDN还为其他浏览器提供了一个 polyfill:
Number.isInteger = Number.isInteger || function(value) {
return typeof value === 'number' &&
isFinite(value) &&
Math.floor(value) === value;
};
但是,对于大多数用例,最好使用Number.isSafeInteger
,它还会检查值是否如此高/低以至于任何小数位都会丢失。 MDN也为此提供了一个 polyfil。 (您还需要上面的isInteger
pollyfill。)
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;
};
为什么不这样:
var isInt = function(n) { return parseInt(n) === n };
您可以使用一个简单的正则表达式:
function isInt(value) {
var er = /^-?[0-9]+$/;
return er.test(value);
}
或者,您也可以根据需要使用以下功能。 它们是由PHPJS Project开发的。
is_int()
=> 检查变量类型是否为整数以及其内容是否为整数
is_float()
=> 检查变量类型是否为浮点数以及其内容是否为浮点数
ctype_digit()
=> 检查变量类型是否为字符串以及其内容是否只有十进制数字
更新 1
现在它也检查负数,感谢@ChrisBartley 的评论!
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
以下是检查值是数字还是可以安全地转换为数字的有效函数:
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)。 这两个解析函数总是先转换为字符串,然后再尝试解析该字符串,如果值已经是数字,这将是一种浪费。
感谢您在这里的其他帖子为优化提供进一步的想法!
function isInt(n)
{
return n != "" && !isNaN(n) && Math.round(n) == n;
}
function isFloat(n){
return n != "" && !isNaN(n) && Math.round(n) != n;
}
适用于所有情况。
这个怎么样?
isFloat(num) {
return typeof num === "number" && !Number.isInteger(num);
}
正如其他人提到的,您在 JS 中只有双打。 那么你如何定义一个数字是一个整数呢? 只需检查四舍五入的数字是否等于自身:
function isInteger(f) {
return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }
这是我用于整数的:
Math.ceil(parseFloat(val)) === val
简短,很好:) 一直有效。 如果我没记错的话,这就是大卫弗拉纳根的建议。
!!(24%1) // false
!!(24.2%1) // true
var isInt = function (n) { return n === (n | 0); };
没有一个案例,这没有做这项工作。
我们可以通过isInteger
函数进行检查。 ie number 将返回 true 并且 float 返回 false
console.log(Number.isInteger(2)),<BR>
将返回真
console.log(Number.isInteger(2.5))
将返回 false
任何小数部分为零的浮点数(例如 1.0、12.00、0.0)都会隐式转换为整数,因此无法检查它们是否为浮点数。
if( n === parseInt(n) ) ...
有道理:如果 JavaScript 可以将某些东西转换为整数,并且通过转换它变成完全相同的东西,那么您的操作数就是整数。
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!
这让很多人感到困惑。 每当某物为 .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位数字应该足以让任何人引用经典。
这实际上取决于您想要实现的目标。 如果您想“模拟”强类型语言,那么我建议您不要尝试。 正如其他人提到的,所有数字都具有相同的表示形式(相同的类型)。
使用类似Claudiu提供的东西:
isInteger( 1.0 )
-> 真
这对于常识来说看起来不错,但在像 C 这样的东西中你会得到false
在这里尝试了一些答案,我最终写了这个解决方案。 这也适用于字符串中的数字。
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);
它真的不必那么复杂。 整数的 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) }
这个解决方案对我有用。
<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>
尝试这个
let n;
return (n = value % 1) !== 0 && !isNaN(n);
当返回值为 false 时表示输入值为浮点数或浮点字符串,否则输入值为整数 numbef 或整数字符串。
基本上它需要检查不等于零的精度值。
另一种是检查正确的字符串编号。
const integerCheck = (num) => {
const isInt = (n) => Number(n) === n && n % 1 === 0
const isFloat = (n) => Number(n) === n && n % 1 !== 0
return (isInt(num) || !isFloat(num))
}
console.log( integerCheck('23.3') );
这是检查整数和浮点数的最终代码
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 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');
}
在 java 脚本中,所有数字都是internally 64 bit floating point
,与 java 中的 double 相同。 javascript 中没有不同的类型,都由类型number
表示。 因此,您将无法进行instanceof
检查。 但是,您可以使用上述给出的解决方案来确定它是否是小数。 Java 脚本的设计者认为使用单一类型可以避免大量类型转换错误。
对于那些好奇的人,我使用 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 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
我喜欢这个小函数,它将对正整数和负整数都返回 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”,其评估结果为真。 我们否定返回值,这给了我们想要的东西。 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 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!
我留下了失败,所以你可以看到每个函数失败的地方,并且(字符串)'#'测试,所以你可以看到每个函数如何处理字符串中的整数和浮点值,因为有些人可能希望将这些解析为数字和一些不得。
在测试的 10 个功能中,真正符合 OP 要求的功能是 [1,3,5,6,8,9]
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提供了以下两个适用于所有数字的函数,包括为-Infinity
和Infinity
返回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
}
}
try this one
function 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');
}
}
您可以使用Number.isInteger()
方法来检查数字是整数还是浮点数,例如:
function isNumberFloatOrInteger(a, b){
if(Number.isInteger(a / b)){
return true;
}
else{ return false };
}
注意: isInteger()
与 Internet Explorer 不兼容。
有 Number.isInteger(number) 来检查这一点。 在 Internet Explorer 中不起作用,但该浏览器不再使用。 如果您需要像“90”这样的字符串作为整数(这不是问题),请尝试 Number.isInteger(Number(number))。 “官方” 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)}
}
}
}
对于整数我使用这个
function integer_or_null(value) {
if ((undefined === value) || (null === value)) {
return null;
}
if(value % 1 != 0) {
return null;
}
return value;
}
根据我在这里看到的所有内容,我创建了自己的一组函数来测试我需要什么:
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;
}
这是我的:
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;
};
浮动验证的条件:
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 values
return false;
else
return 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 values
return false;
else
return !!(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 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。
我知道已经有 30 个答案,但一种复杂的方法是这样做:
function isInteger(n) {
return n.toString().split('.').length === 1;
}
解释:我们首先将n
转换为字符串,并以点为单位进行拆分。 如果n
是浮点数,例如4.5
,则 split 将返回一个数组['4', '5']
。 如果它是像45
这样的整数,它将返回['45']
。 因此,如果数组的长度为 1,那么我们就知道它是一个数字。
PS 如果你想用新的 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; }
2022 年更新 - 我们可以简单地使用 Number 的方法。
检查 integer 或浮点数: Number.isFinite(val)
检查 integer: Number.isInteger(val)
检查是否浮点数(不是整数): .Number.isInteger(val) && Number isFinite(val)
const isInt = n => n % 1 === true
const isFloat = n => n % 1 == true
我迟到了,但这是我的版本
isInteger: obj => Number.isInteger(!isNaN(obj % 1) && obj % 1 !== 0 ? obj : parseInt(obj)),
另一种方法是:
function isFloat(float) {
return /\./.test(float.toString());
}
可能不如其他方法有效,但另一种方法都一样。
parseInt(yourNumber)=== parseFloat(yourNumber)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.