How can I check if a string is a float?

前端 未结 14 1770
清歌不尽
清歌不尽 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:23

    use this jquery code

        <script>
        $(document).ready(function () {
            $(".allow_only_float").keypress(function (e) {
    
                if (e.which != 46 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                    e.preventDefault();//return false;
                }
                var avg = $('#<%=txtAverage.ClientID%>').val();
                var idx = avg.indexOf(".");
                if (idx > -1 && e.which == 46) {
                    e.preventDefault();//return false;
                }
            });
        });
        </script>
    <body>
        <input type='text' class='allow_only_float'>
    </body>
    
    0 讨论(0)
  • 2020-12-23 20:26

    To check if a string is an integer or a float

    function isFloat(n) {
        return parseFloat(n.match(/^-?\d*(\.\d+)?$/))>0;
    }
    
    //alert(isFloat("3.444"));
    
    0 讨论(0)
  • 2020-12-23 20:26

    This function returns the numeric value of a string regardless if int or float

    function getNumericVal(str) {
        if(isNaN(str)) return;
        try {return parseFloat(str);} 
        catch(e) {return parseInt(str);}
    }
    
    0 讨论(0)
  • 2020-12-23 20:28

    straight forward:

    if (parseFloat(value).toString() === value.toString()) {
        ...
    }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-12-23 20:31
    function checkFloat(value) {
        let parsed = Number.parseFloat(value);
        return (!Number.isNaN(parsed)) && (!Number.isInteger(parsed))
    }
    
    0 讨论(0)
提交回复
热议问题