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

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

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
	}
}