Check if a string is numeric

How do you check if a string is numeric (just a number) in Unity JS?

2 Answers

2

Look into the various Parse or TryParse methods of the primitive numeric data-types. They attempt to convert a string into the corresponding numerical datatype, if possible. Try this, for example:

This method automatically handles the FormatException that otherwise gets thrown if the strong was not a double. If it is numerical and can be converted to a double, it returns true, if not, it returns false.

How do you apply this for UnityScript?

Just call the method like you would any other method in Unityscript? I code in C#, but I imagine it would be something like var yourDouble : double; if(Double.TryParse("32.0", out yourDouble)) // 32.0 is just an example { // Numerical! } else { // Not numerical! }

Okay, typing code directly into a comment box doesn't work terribly well. :) Sorry. Try to paste it into your editor, maybe it will format it better.

The best overloaded method match for `double.TryParse(string, out double)' has some invalid arguments

The question is what do you consider as “just a number”? Only integer values? only positive values? Here’s a small list of possible number-strings:

"100"
"-123,456,789"
"123.45e+6"
"+500"
"5e2"
"3.1416"
"600."
"-.123" 
"-Infinity"
"-1E-16"

Taken from the float.Parse() page.

Basically, the equivalent to Flash's NaN or VB's isNumeric... That is, Sally137.0 is not numeric but 137.0 is! (along with all the numeric formats you listed above...)