- Home /
Is it possible for parseInt("5+5") to return 10?
Hey guys, is it possible to parse a string into an int/float, while also applying all the basic math operations? (+,-,/,*)? Example
var theString : String = "10*(9-6)+25/5";
var theInt : int = parse(theString);
print(theInt); //this should print 35.
Does a function that provides this functionality exist, or should I write my own?
David
there has just got to be a library somewhere that does that!
Answer by numberkruncher · Feb 21, 2013 at 05:43 PM
You will usually need to implement an expression parser to evaluate such a string.
In UnityScript you might be able to use the eval
function. But be very careful, many consider this function to be evil. You will likely need to use an exception trap. To improve matters you should pre-validate your input expression using a regex that only accepts the expected digit and symbol characters.
function Awake() {
try {
var expression : String = '10 + 4 * (9-6)';
var validatePattern : Regex = new Regex('^[0-9\\.+/*\\(\\)\\- ]+$');
if (expression != '' && validatePattern.IsMatch(expression)) {
var result : int = parseInt(eval(expression));
Debug.Log(result);
}
}
catch (e) {
// handle the syntax/evaluation error
}
}
@dzebna Sorry, it appears that UnityScript does not support regex literals. I will amend with the long-hand version...
This doesn't work either, it say 'Interface member implementation must be public or explicit' 3 times I think I will just drop this idea entirely then. I think it's an eval bug.
I believe that 'Interface member implementation must be public or explicit'
occurs when you have not implemented an interface member correctly.
public class Something : ISomeInterface {
// Option #1 : Public
public void AnInterface$$anonymous$$ethod() {}
// Option #2 : Explicit
void ISomeInterface.AnInterface$$anonymous$$ethod() {}
}
Note: The above is C# because I do not know the UnityScript syntax for option #2 :S
I tried setting the class and the Awake function to public, but that didn't work either :/
Answer by Hannibalov · Feb 21, 2013 at 04:50 PM
I don't think that's included either in .net nor in unity. If you do the math with floats, however, you can always call .ToString() with the result. If for some reason you need to have strings, you should write your own parser
Your answer
Follow this Question
Related Questions
Extract number from string? 3 Answers
parseInt givin' me issues! 2 Answers
BCE0022: Cannot convert 'String' to 'int'. 0 Answers
Download a WWW int? Or convert? 1 Answer
GetHashCode() questions/Turning a text string into an int 1 Answer