Search code examples
javascriptparsefloat

Is it possible to parseFloat the whole string?


As you know, the javascript's parseFloat function works only until it meets an invalid character, so for example

parseFloat("10.123") = 10.123
parseFloat("12=zzzz") = 12
parseFloat("z12") = NaN

Is there a way or an implementation of parseFloat that would return NaN if the whole string is not a valid float number?


Solution

  • Use this instead:

    var num = Number(value);
    

    Then you can do:

    if (isNaN(num)) {
        // take proper action
    }