1

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.

3 Answers 3

4

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+)?/
Sign up to request clarification or add additional context in comments.

5 Comments

For implementation's sake, str = str.match(/[0-9]+.?[0-9]*/g).toString();.
@OXMO456 +1 for showing a specific-match approach (I'm assuming the problems in the post will be fixed ;-). However, this will fail to match ".123" and will match "123_456" and the use of /g is suspect as it then opens it up to match "1.2 blah blah blah 1.4" (will result in "1.2,1.4" after string-ification and thus is "useless" for this task). Also, [0-9] is more cleanly written as \d, IMOHO
@pst yes, this is not the 'perfect' regex but it's a start ; ) it could be refactored depending on the context and needs !
@pst i agree with you, but the question is already marked as answered so... thank for the +1 btw : )
/-?\d*\.?\d+([eE]\d+)?/ may be better. It catches .123
1

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.

2 Comments

Your call to replace has a major fault in it. Try the string "w10w10w.w10" to see what I mean. You should say this instead: replace(/^\D*/g, ""). The uncut noise after the number will be ignored by the parse functions.
For my purposes this works perfectly, since the user won't be able to play around with the signs, and isn't allowed to input letters or special characters besides a dot.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.