(Built-in) way in JavaScript to check if a string is a valid number

前端 未结 30 3354
-上瘾入骨i
-上瘾入骨i 2020-11-22 01:54

I\'m hoping there\'s something in the same conceptual space as the old VB6 IsNumeric() function?

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 02:43

    Why is jQuery's implementation not good enough?

    function isNumeric(a) {
        var b = a && a.toString();
        return !$.isArray(a) && b - parseFloat(b) + 1 >= 0;
    };
    

    Michael suggested something like this (although I've stolen "user1691651 - John"'s altered version here):

    function isNumeric(num){
        num = "" + num; //coerce num to be a string
        return !isNaN(num) && !isNaN(parseFloat(num));
    }
    

    The following is a solution with most likely bad performance, but solid results. It is a contraption made from the jQuery 1.12.4 implementation and Michael's answer, with an extra check for leading/trailing spaces (because Michael's version returns true for numerics with leading/trailing spaces):

    function isNumeric(a) {
        var str = a + "";
        var b = a && a.toString();
        return !$.isArray(a) && b - parseFloat(b) + 1 >= 0 &&
               !/^\s+|\s+$/g.test(str) &&
               !isNaN(str) && !isNaN(parseFloat(str));
    };
    

    The latter version has two new variables, though. One could get around one of those, by doing:

    function isNumeric(a) {
        if ($.isArray(a)) return false;
        var b = a && a.toString();
        a = a + "";
        return b - parseFloat(b) + 1 >= 0 &&
                !/^\s+|\s+$/g.test(a) &&
                !isNaN(a) && !isNaN(parseFloat(a));
    };
    

    I haven't tested any of these very much, by other means than manually testing the few use-cases I'll be hitting with my current predicament, which is all very standard stuff. This is a "standing-on-the-shoulders-of-giants" situation.

提交回复
热议问题