How can I check if a string is a float?

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

提交回复
热议问题