Search code examples
javascriptparseintparsefloat

parseFloat() from the middle of the string


I always have a "NaN" when wanted to "parseInt or parseFloat" from string like "Sometext 330"

Var a = "Sometext 330"
return parseFloat(a);

and it will return "NaN" but i need integer or float 330


Solution

  • You could sanitize your string first so only digit's remain in the string before parsing the number.

    edit: now it's even safer as it will accept Number types without blowing up.

    var a = "Sometext 330"
    
    function safeParseFloat(val) {
      return parseFloat(isNaN(val) ? val.replace(/[^\d\.]+/g, '') : val)
    }
    
    function superSafeParseFloat(val) {
      if (isNaN(val)) {
        if ((val = val.match(/([0-9\.,]+\d)/g))) {
          val = val[0].replace(/[^\d\.]+/g, '')
        }
      }
      return parseFloat(val)
    }
    
    console.log(
      safeParseFloat(a),
      safeParseFloat(2000.69)
    )
    
    console.log(
      superSafeParseFloat('blah $2,000,000.69 AUD'),
      superSafeParseFloat('blah $8008 USD'),
      superSafeParseFloat('NotANumber'),
      superSafeParseFloat(8008.69),
      superSafeParseFloat('... something 500.5... test')
    )