How can I check if a string is a float?

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

    You can use the parseFloat function.

    If the value passed begins with what looks like a float, the function returns the value converted to a float, otherwise it will return NaN.

    Something like:

    function beginsWithFloat(val) {
      val = parseFloat(val);
      return ! isNaN(val);
    }
    console.log(beginsWithFloat("blabla")); // shows false
    console.log(beginsWithFloat("123blabla")); // shows true

    0 讨论(0)
  • 2020-12-23 20:49

    To check if a string is a float (avoid int values)

    function isFloat(n) {
       if( n.match(/^-?\d*(\.\d+)?$/) && !isNaN(parseFloat(n)) && (n%1!=0) )
          return true;
       return false;
    }
    
    var nonfloat = isFloat('12'); //will return false
    var nonfloat = isFloat('12.34abc'); //will return false
    var float = isFloat('12.34'); //will return true
    
    0 讨论(0)
提交回复
热议问题