Skip to main content
Inspiring
October 28, 2007
Question

Annoying String to Float in AS3

  • October 28, 2007
  • 2 replies
  • 1058 views
Hey again,

I am working on *AS3* here.

Problem: I have a value stored in a String. I'd like to check whether
that String is a float. I am aware of the method parseFloat(string)
described here:
http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/
actionscript_dictionary620.html
However, this method has annoying limitations:
parseFloat("2.5") will be 2.5
parseFloat(" 2.5") will be 2.5
parseFloat("2.5garbage") will be 2.5
parseFloat("2.5garbage3.2") will be 2.5
it will only be NaN if the value of the string starts with a non-
numerical character
parseFloat("garbage2.5") will be NaN

So doing something like that, will not work for me:
public function isFloat : Boolean(str : String) {
if (isNaN(parseFloat(str))) {
return false;
}
return true;
}

I want to check if the string is a *real* float that is:
isFloat("2.5") will be true
isFloat("x2.5") will be false
isFloat("2.5x3.2") will be false
isFloat("2.5x") will be false
Basically, no spaces or non-numerical characters should be allowed
(expect the one dot '.' if required).

I'm thinking of implementing my own isFloat method, checking character by
character to see if the value is really a float or not. Something like
that (quick draft, haven't tested it or compiled it):

public function isFloat : Boolean (str : String) {
var dotUsed : Boolean = false;
for (var i : int = 0; i < str.length; ++i) {
if (str.charAt(i) == '.') {
if (!dotUsed) {
dotUsed = true;
} else {
return false;
}
} else if (isNaN(parseInt(str.charAt(i)))) {
return false;
}
}
}

However, I'm not happy with the runtime efficiency here. I'm sure there's
some more efficient way to detect that a string is a float; or another
simple method I haven't look at.

Any thoughts?

Thanks
This topic has been closed for replies.

2 replies

Inspiring
October 28, 2007
That's a good idea actually. I wonder why I haven't though of it earlier.
Something like that should do it:

public function isFloat (str: String) : Boolean {
static var re : RegExp = new RegExp('([0-9]+(\.[0-9]*)?)|(\.[0-9]+)');
return re.test(str);
}

If other ideas come up, please let me know.
Thanks again.
Inspiring
October 28, 2007
You can avoid the looping test by using a regular expression. Basically the whole check could be done with a regular expression. I'd love to provide the code, but regular expressions are new to me as well. I had a play around with them and got close, but it didn't pass all the tests, so I wasn't doing something right. Someone else will post an example I'm sure.