在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

当前回答

如果typeof n==“string”,则需要检查空/未定义条件并删除逗号(对于美国数字格式)。

function isNumeric(n)
{
    if(n === null || typeof n === 'undefined')
         return false;

    if(typeof n === 'string')
        n = n.split(',').join('');

    return !isNaN(parseFloat(n)) && isFinite(n);
}

https://jsfiddle.net/NickU/nyzeot03/3/

其他回答

它可以在没有RegExp的情况下作为

function IsNumeric(data){
    return parseFloat(data)==data;
}

我觉得我的代码很完美。。。

/***@param{string}s*@return{boolean}*/var isNumber=函数{return s.trim()=="" && !isNaN(数字);};

function isNumeric(n) {
    var isNumber = true;

    $.each(n.replace(/ /g,'').toString(), function(i, v){
        if(v!=',' && v!='.' && v!='-'){
            if(isNaN(v)){
               isNumber = false;
               return false;
            }
         }
     });

    return isNumber;
}

isNumeric(-3,4567.89);   // true <br>

isNumeric(3,4567.89);   // true <br>

isNumeric("-3,4567.89");   // true <br>

isNumeric(3d,4567.89);   // false

是的,内置的isNaN(对象)将比任何正则表达式解析都快得多,因为它是内置和编译的,而不是动态解释的。

尽管结果与您想要的有所不同(尝试一下):

                                              // IS NUMERIC
document.write(!isNaN('-1') + "<br />");      // true
document.write(!isNaN('-1.5') + "<br />");    // true
document.write(!isNaN('0') + "<br />");       // true
document.write(!isNaN('0.42') + "<br />");    // true
document.write(!isNaN('.42') + "<br />");     // true
document.write(!isNaN('99,999') + "<br />");  // false
document.write(!isNaN('0x89f') + "<br />");   // true
document.write(!isNaN('#abcdef') + "<br />"); // false
document.write(!isNaN('1.2.3') + "<br />");   // false
document.write(!isNaN('') + "<br />");        // true
document.write(!isNaN('blah') + "<br />");    // false

@CMS的回答:您的代码段在我的机器上使用nodejs处理空白情况时失败。所以我把它和@joel对以下问题的回答:

is_float = function(v) {
    return !isNaN(v) && isFinite(v) &&
        (typeof(v) == 'number' || v.replace(/^\s+|\s+$/g, '').length > 0);
}

我用那些浮动的案例对其进行了统一测试:

var t = [
        0,
        1.2123,
        '0',
        '2123.4',
        -1,
        '-1',
        -123.423,
        '-123.432',
        07,
        0xad,
        '07',
        '0xad'
    ];

以及那些没有浮点数的情况(包括空白空格和对象/数组):

    var t = [
        'hallo',
        [],
        {},
        'jklsd0',
        '',
        "\t",
        "\n",
        ' '
    ];

这里的一切都按预期进行。也许这有帮助。

这里可以找到完整的源代码。