Check if character is number?

前端 未结 22 605
误落风尘
误落风尘 2020-12-03 00:29

I need to check whether justPrices[i].substr(commapos+2,1).

The string is something like: \"blabla,120\"

In this case it would check whether \'0

相关标签:
22条回答
  • 2020-12-03 00:42

    You can use this:

    function isDigit(n) {
        return Boolean([true, true, true, true, true, true, true, true, true, true][n]);
    }
    

    Here, I compared it to the accepted method: http://jsperf.com/isdigittest/5 . I didn't expect much, so I was pretty suprised, when I found out that accepted method was much slower.

    Interesting thing is, that while accepted method is faster correct input (eg. '5') and slower for incorrect (eg. 'a'), my method is exact opposite (fast for incorrect and slower for correct).

    Still, in worst case, my method is 2 times faster than accepted solution for correct input and over 5 times faster for incorrect input.

    0 讨论(0)
  • 2020-12-03 00:43

    Try:

    function is_numeric(str){
            try {
               return isFinite(str)
            }
            catch(err) {
                return false
            }
        }
    
    0 讨论(0)
  • 2020-12-03 00:43
    square = function(a) {
        if ((a * 0) == 0) {
            return a*a;
        } else {
            return "Enter a valid number.";
        }
    }
    

    Source

    0 讨论(0)
  • 2020-12-03 00:45

    You can try this (worked in my case)

    If you want to test if the first char of a string is an int:

    if (parseInt(YOUR_STRING.slice(0, 1))) {
        alert("first char is int")
    } else {
        alert("first char is not int")
    }
    

    If you want to test if the char is a int:

    if (parseInt(YOUR_CHAR)) {
        alert("first char is int")
    } else {
        alert("first char is not int")
    }
    
    0 讨论(0)
  • 2020-12-03 00:48

    EDIT: Blender's updated answer is the right answer here if you're just checking a single character (namely !isNaN(parseInt(c, 10))). My answer below is a good solution if you want to test whole strings.

    Here is jQuery's isNumeric implementation (in pure JavaScript), which works against full strings:

    function isNumeric(s) {
        return !isNaN(s - parseFloat(s));
    }
    

    The comment for this function reads:

    // parseFloat NaNs numeric-cast false positives (null|true|false|"")
    // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
    // subtraction forces infinities to NaN

    I think we can trust that these chaps have spent quite a bit of time on this!

    Commented source here. Super geek discussion here.

    0 讨论(0)
  • 2020-12-03 00:48
    function is_numeric(mixed_var) {
        return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') &&
            mixed_var !== '' && !isNaN(mixed_var);
    }
    

    Source code

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