Michael Shtefanitsa
Michael Shtefanitsa

Reputation: 303

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

Upvotes: 0

Views: 1506

Answers (4)

Megukaphii
Megukaphii

Reputation: 51

If you want it to parse floats/to float, you could use this regex:

    var numberStr = "fea$420.69atrg";
    return parseFloat(numberStr.match(/\d+\.\d+/)[0]);

That'll return 420.69 here.

Upvotes: 0

synthet1c
synthet1c

Reputation: 6282

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')
)

Upvotes: 7

Dennington-bear
Dennington-bear

Reputation: 1782

You can also split the string too if your use case is always the same.

var str = "test 900";
var split = str.split(' ');
// Loop through the split array
split.forEach(function(item){
  // If the split is not NaN
  if(!isNaN(item)){
    // Heres your number
    console.log(item);
  }
});

Upvotes: 1

Mojo Allmighty
Mojo Allmighty

Reputation: 793

More elegant way :

Var a = "Sometext 330"
return parseFloat(a.match(/\d+$/)[0]);

Upvotes: 0

Related Questions