℡Wang Yan 2008-08-20 14:21 采纳率: 100%
浏览 231
已采纳

在 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

  • 写回答

27条回答 默认 最新

  • larry*wei 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));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(26条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c