enon
enon

Reputation: 451

Extracting an integer from a string?

How do I extract the numbers out of a string like this:

$1.50

Everything but the currency symbol. Or from something like this:

rofl1.50lmao

Just asking if there's an existing function that I'm not a aware of.

Upvotes: 1

Views: 442

Answers (3)

OXMO456
OXMO456

Reputation: 3548

There is no builtin function in AS3 for that. A simple RegExp like this one should help you :

/[0-9]+.?[0-9]*/

This is an example, and should be refactored depending your context.

Here is a more precise RegEx from Gunslinger47:

/-?\d*\.?\d+([eE]\d+)?/

Upvotes: 4

user166390
user166390

Reputation:

This is "plain" JavaScript, but FWIW:

justNumsAndDots = "rofl1.50lmao".replace(/[^\d.]/g,"") // -> "1.50" (string)
asIntegral = parseInt("0" + justNumsAndDots, 10)       // -> 1 (number)
asNumber = parseFloat("0" + justNumsAndDots)           // -> 1.5 (number)
asTwoDecimalPlaces = (2 + asNumber).toFixed(2)         // -> "3.50" (string)

Notes:

  1. Doesn't take localization into account.
  2. Radix (base-10) is passed to parseInt to avoid potential octal conversion (not sure if this "issue" plagues AS).
  3. "0" is added to the start of justNumsAndDots so parseInt/parseFloat will never return a NaN here. (e.g. parseFloat(".") -> NaN, parseFloat("0.") -> 0). If NaN's are desired, alter to suite.
  4. Input like "rofl1.chopter50lolz" will be stripped to "1.50", it might be over-greedy, depending.
  5. Adapt to AS as necessary.

Happy coding.

Upvotes: 1

Jorjon
Jorjon

Reputation: 5434

As far as I know, no. You can parse every character against an array of valid characters, or use regexp.

Upvotes: 1

Related Questions