Check if character is number?

前端 未结 22 604
误落风尘
误落风尘 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: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.

提交回复
热议问题