How can I check if a string is a float?

前端 未结 14 1833
清歌不尽
清歌不尽 2020-12-23 20:21

I am passing in a parameter called value. I\'d like to know if value is a float. So far, I have the following:

if (!isNaN(value))
{
    alert(\'this is a num         


        
14条回答
  •  长情又很酷
    2020-12-23 20:30

    Following functions also check for format. E.g. JavaScript native parseInt and parseFloat functions also parse strings containing non numeric characters, and functions above have consequences of this.

    // For example, following code will work
    var n = parseInt('123asd');
    n == 123
    

    These functions will return false for such string.

    function isFloat(val) {
        var floatRegex = /^-?\d+(?:[.,]\d*?)?$/;
        if (!floatRegex.test(val))
            return false;
    
        val = parseFloat(val);
        if (isNaN(val))
            return false;
        return true;
    }
    
    function isInt(val) {
        var intRegex = /^-?\d+$/;
        if (!intRegex.test(val))
            return false;
    
        var intVal = parseInt(val, 10);
        return parseFloat(val) == intVal && !isNaN(intVal);
    }
    

提交回复
热议问题