在JavaScript中验证十进制数字最干净、最有效的方法是什么?

奖励积分:

清晰解决方案应干净简单。跨平台。

测试用例:

01. IsNumeric('-1')      => true
02. IsNumeric('-1.5')    => true
03. IsNumeric('0')       => true
04. IsNumeric('0.42')    => true
05. IsNumeric('.42')     => true
06. IsNumeric('99,999')  => false
07. IsNumeric('0x89f')   => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3')   => false
10. IsNumeric('')        => false
11. IsNumeric('blah')    => false

当前回答

function IsNumeric(num) {
     return (num >=0 || num < 0);
}

这也适用于0x23类型编号。

其他回答

整数值可通过以下方式验证:

function isNumeric(value) {
    var bool = isNaN(+value));
    bool = bool || (value.indexOf('.') != -1);
    bool = bool || (value.indexOf(",") != -1);
    return !bool;
};

这种方式更容易、更快!检查所有测试!

这种方式似乎很有效:

function IsNumeric(input){
    var RE = /^-{0,1}\d*\.{0,1}\d+$/;
    return (RE.test(input));
}

在一行中:

const IsNumeric = (num) => /^-{0,1}\d*\.{0,1}\d+$/.test(num);

要测试它:

常量IsNumeric=(num)=>/^-{0,1}\d*\。{0,1}\d+$/.test(num);函数TestIsNumeric(){var结果=“”results+=(IsNumeric('-1')?“通过”:“失败”)+“:IsNumeric('-1')=>true\n”;结果+=(IsNumeric('-1.5')?“通过”:“失败”)+“:IsNumeric('-1.5')=>true\n”;结果+=(IsNumeric(“0”)?“通过”:“失败”)+“:IsNumeric('0')=>true\n”;结果+=(IsNumeric(“0.42”)?“通过”:“失败”)+“:IsNumeric('0.42')=>true\n”;results+=(IsNumeric('.42')?“通过”:“失败”)+“:IsNumeric('.42')=>true\n”;results+=(!IsNumeric('99999')?“通过”:“失败”)+“:IsNumeric(‘99999’)=>false \n”;results+=(!IsNumeric('0x89f')?“通过”:“失败”)+“:IsNumeric('0x89f')=>false \n”;results+=(!IsNumeric('#abcdef')?“通过”:“失败”)+“:IsNumeric('#abcdef')=>false \n”;results+=(!IsNumeric('1.2.3')?“通过”:“失败”)+“:IsNumeric('1.2.3')=>false \n”;results+=(!IsNumeric(“”)?“通过”:“失败”)+“:IsNumeric(“”)=>false \n”;results+=(!IsNumeric('barh')?“通过”:“失败”)+“:IsNumeric('barh')=>false \n”;返回结果;}console.log(TestIsNumeric());.作为控制台包装{最大高度:100%!重要;顶部:0;}

我从那里借来的正则表达式http://www.codetoad.com/javascript/isnumeric.asp.说明:

/^ match beginning of string
-{0,1} optional negative sign
\d* optional digits
\.{0,1} optional decimal point
\d+ at least one digit
$/ match end of string

对于空字符串,没有一个答案返回false,对此进行了修复。。。

function is_numeric(n)
{
 return (n != '' && !isNaN(parseFloat(n)) && isFinite(n));
}
function isNumber(n) {
    return (n===n+''||n===n-0) && n*0==0 && /\S/.test(n);
}

解释:

(n===n-0||n===n+'')验证n是数字还是字符串(丢弃数组、布尔值、日期、空值…)。您可以用n替换(n===n-0|| n===n+'')==未定义&&n==null&&(n.constructor==数字||n.constructor==字符串):明显更快,但不那么简洁。

n*0==0验证n是否是有限数,正如isFinite(n)所做的那样。如果您需要检查表示负十六进制的字符串,只需将n*0==0替换为类似于n.toString().replace(/^\s*-/,'')*0==0。当然,它需要一点钱,所以如果你不需要它,就不要使用它。

/\S/.test(n)丢弃空字符串或只包含空格的字符串(这是必要的,因为在这种情况下isFinite(n)或n*0==0返回假阳性)。您可以使用(n!=0||/0/.test(n))而不是\\S/.test(n)来减少对.test(n)的调用次数,也可以使用稍快但不太简洁的测试,例如(n!=0 | |(n+'').indexOf('0')>=0):微小的改进。

我认为parseFloat函数可以完成这里的所有工作。下面的函数通过了此页面上的所有测试,包括isNumeric(Infinity)==true:

function isNumeric(n) {

    return parseFloat(n) == n;
}