我希望在与旧的VB6 IsNumeric()函数相同的概念空间中有什么东西?
当前回答
如果要查找正数(例如门牌号),请使用:
if (mystring > 0) ...
其他回答
报价:
isNaN(num)//如果变量不包含有效数字,则返回true
如果您需要检查前导/尾随空格,则不完全正确-例如,当需要一定数量的数字时,并且您需要获得例如“1111”而不是“111”或“111”以获得PIN输入。
更好使用:
var num = /^\d+$/.test(num)
我的解决方案:
// returns true for positive ints;
// no scientific notation, hexadecimals or floating point dots
var isPositiveInt = function(str) {
var result = true, chr;
for (var i = 0, n = str.length; i < n; i++) {
chr = str.charAt(i);
if ((chr < "0" || chr > "9") && chr != ",") { //not digit or thousands separator
result = false;
break;
};
if (i == 0 && (chr == "0" || chr == ",")) { //should not start with 0 or ,
result = false;
break;
};
};
return result;
};
您可以在循环中添加其他条件,以满足您的特定需求。
它对TypeScript无效,因为:
声明函数isNaN(数字:数字):布尔值;
对于TypeScript,您可以使用:
/^\d+$/.测试(键)
有些人也可能从基于正则表达式的答案中受益。这里是:
一行是Integer:
const isInteger = num => /^-?[0-9]+$/.test(num+'');
一行是Numeric:接受整数和小数
const isNumeric = num => /^-?[0-9]+(?:\.[0-9]+)?$/.test(num+'');
这个问题的公认答案有很多缺陷(正如其他几位用户所强调的)。这是用javascript实现它的最简单且经过验证的方法之一:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
以下是一些好的测试用例:
console.log(isNumeric(12345678912345678912)); // true
console.log(isNumeric('2 ')); // true
console.log(isNumeric('-32.2 ')); // true
console.log(isNumeric(-32.2)); // true
console.log(isNumeric(undefined)); // false
// the accepted answer fails at these tests:
console.log(isNumeric('')); // false
console.log(isNumeric(null)); // false
console.log(isNumeric([])); // false