在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 inNumeric(n){
   return Number(n).toString() === n;
}

如果n是数字,Number(n)将返回数值,toString()将返回字符串。但如果n不是数字,则Number(n)将返回NaN,因此它将与原始n不匹配

雅虎!UI使用此项:

isNumber: function(o) {
    return typeof o === 'number' && isFinite(o);
}

在这里,我从这个页面收集了“好的”,并将它们放入一个简单的测试模式中,供您自行评估。

对于新手来说,console.log是一个内置函数(在所有现代浏览器中都可用),它允许您将结果输出到JavaScript控制台(仔细查看,您会发现),而不必输出到HTML页面。

var isNumeric = function(val){
    // --------------------------
    // Recommended
    // --------------------------

    // jQuery - works rather well
    // See CMS's unit test also: http://dl.getdropbox.com/u/35146/js/tests/isNumber.html
    return !isNaN(parseFloat(val)) && isFinite(val);

    // Aquatic - good and fast, fails the "0x89f" test, but that test is questionable.
    //return parseFloat(val)==val;

    // --------------------------
    // Other quirky options
    // --------------------------
    // Fails on "", null, newline, tab negative.
    //return !isNaN(val);

    // user532188 - fails on "0x89f"
    //var n2 = val;
    //val = parseFloat(val);
    //return (val!='NaN' && n2==val);

    // Rafael - fails on negative + decimal numbers, may be good for isInt()?
    // return ( val % 1 == 0 ) ? true : false;

    // pottedmeat - good, but fails on stringy numbers, which may be a good thing for some folks?
    //return /^-?(0|[1-9]\d*|(?=\.))(\.\d+)?$/.test(val);

    // Haren - passes all
    // borrowed from http://www.codetoad.com/javascript/isnumeric.asp
    //var RE = /^-{0,1}\d*\.{0,1}\d+$/;
    //return RE.test(val);

    // YUI - good for strict adherance to number type. Doesn't let stringy numbers through.
    //return typeof val === 'number' && isFinite(val);

    // user189277 - fails on "" and "\n"
    //return ( val >=0 || val < 0);
}

var tests = [0, 1, "0", 0x0, 0x000, "0000", "0x89f", 8e5, 0x23, -0, 0.0, "1.0", 1.0, -1.5, 0.42, '075', "01", '-01', "0.", ".0", "a", "a2", true, false, "#000", '1.2.3', '#abcdef', '', "", "\n", "\t", '-', null, undefined];

for (var i=0; i<tests.length; i++){
    console.log( "test " + i + ":    " + tests[i] + "    \t   " + isNumeric(tests[i]) );
}

可以使用类型检查库,如https://github.com/arasatasaygin/is.js或者从那里提取一个检查片段(https://github.com/arasatasaygin/is.js/blob/master/is.js#L131):

is.nan = function(value) {    // NaN is number :) 
  return value !== value;
};
 // is a given value number?
is.number = function(value) {
    return !is.nan(value) && Object.prototype.toString.call(value) === '[object Number]';
};

通常,如果您需要它来验证参数类型(在函数调用的入口点),您可以使用符合JSDOC的契约(https://www.npmjs.com/package/bycontract):

/**
 * This is JSDOC syntax
 * @param {number|string} sum
 * @param {Object.<string, string>} payload
 * @param {function} cb
 */
function foo( sum, payload, cb ) {
  // Test if the contract is respected at entry point
  byContract( arguments, [ "number|string", "Object.<string, string>", "function" ] );
}
// Test it
foo( 100, { foo: "foo" }, function(){}); // ok
foo( 100, { foo: 100 }, function(){}); // exception

我想补充以下内容:

1. IsNumeric('0x89f') => true
2. IsNumeric('075') => true

正十六进制数以0x开头,负十六进制数则以-0x开头。正八进制数从0开始,负八进制数以-0开始。这一条考虑了已经提到的大部分内容,但包括十六进制和八进制数、负科学数、无穷大数,并删除了十进制科学数(4e3.2无效)。

function IsNumeric(input){
  var RE = /^-?(0|INF|(0[1-7][0-7]*)|(0x[0-9a-fA-F]+)|((0|[1-9][0-9]*|(?=[\.,]))([\.,][0-9]+)?([eE]-?\d+)?))$/;
  return (RE.test(input));
}