An improved isNumeric() function?

前端 未结 7 1603
轮回少年
轮回少年 2021-02-01 14:00

During some projects I have needed to validate some data and be as certain as possible that it is javascript numerical value that can be used in mathematical operations.

相关标签:
7条回答
  • 2021-02-01 14:32

    If it's OK for you to use regular expressions, this might do the trick:

    function (n) 
        { 
        return (Object.prototype.toString.call(n) === '[object Number]' ||
                Object.prototype.toString.call(n) === '[object String]') && 
               (typeof(n) != 'undefined')  &&  (n!=null) && 
               (/^-?\d+((.\d)?\d*(e[-]?\d)?(\d)*)$/.test(n.toString()) ||
               /^-?0x[0-9A-F]+$/.test(n.toString()));
        }
    

    edit: Fixed problem with hex numbers

    0 讨论(0)
  • 2021-02-01 14:35

    isNaN function used to check the value is a numeric or not. If the values is numeric its return true else returned false.

    code:

     <script>
    
             function IsNumeric(val) {
    
                  if (isNaN(parseFloat(val))) {
    
                     return false;
    
              }
    
              return true
    
      }
    
    
      bool IsNumeric(string);
    
    
    </script>
    
    0 讨论(0)
  • 2021-02-01 14:38
    function isNumber(value){return typeof value == 'number';}
    
    0 讨论(0)
  • 2021-02-01 14:39

    In my opinion, if it's an array then its not numeric. To alleviate this problem, I added a check to discount arrays from the logic

    You can have that problem with any other object as well, for example {toString:function(){return "1.2";}}. Which objects would you think were numeric? Number objects? None?

    Instead of trying to blacklist some things that fail your test, you should explicitly whitelist the things you want to be numeric. What is your function supposed to get, primitive strings and numbers? Then test exactly for them:

    (typeof n == "string" || typeof n == "number")
    
    0 讨论(0)
  • 2021-02-01 14:43

    How about:

    function isNumber(value) {
      value = Number(value);
      return typeof value === 'number' && !isNaN(value) && isFinite(value);
    }
    
    0 讨论(0)
  • 2021-02-01 14:56

    If AMD sounds good to you, have a look at mout's isNumber().

    0 讨论(0)
提交回复
热议问题