elliott.david 2008-08-20 14:21 采纳率: 25%
浏览 290
已采纳

在 JavaScript-IsNumeric ()中验证十进制数

What's the cleanest, most effective way to validate decimal numbers in JavaScript?

Bonus points for:

  1. Clarity. Solution should be clean and simple.
  2. Cross-platform.

Test cases:

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

转载于:https://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric

  • 写回答

28条回答 默认 最新

  • Lotus@ 2013-07-09 23:10
    关注

    @Joel's answer is pretty close, but it will fail in the following cases:

    // Whitespace strings:
    IsNumeric(' ')    == true;
    IsNumeric('\t\t') == true;
    IsNumeric('\n\r') == true;
    
    // Number literals:
    IsNumeric(-1)  == false;
    IsNumeric(0)   == false;
    IsNumeric(1.1) == false;
    IsNumeric(8e5) == false;
    

    Some time ago I had to implement an IsNumeric function, to find out if a variable contained a numeric value, regardless of its type, it could be a String containing a numeric value (I had to consider also exponential notation, etc.), a Number object, virtually anything could be passed to that function, I couldn't make any type assumptions, taking care of type coercion (eg. +true == 1; but true shouldn't be considered as "numeric").

    I think is worth sharing this set of +30 unit tests made to numerous function implementations, and also share the one that passes all my tests:

    function isNumeric(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }
    

    P.S. isNaN & isFinite have a confusing behavior due to forced conversion to number. In ES6, Number.isNaN & Number.isFinite would fix these issues. Keep that in mind when using them.


    Update : Here's how jQuery does it now (2.2-stable):

    isNumeric: function(obj) {
        var realStringObj = obj && obj.toString();
        return !jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0;
    }
    

    Update : Angular 4.3:

    export function isNumeric(value: any): boolean {
        return !isNaN(value - parseFloat(value));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(27条)

报告相同问题?

悬赏问题

  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案