function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
kevoharakevohara 

String containing an expression...how to calculate it and return a Decimal?

Suppose I have a string that contains an expression...

 

String exp = '25.4 + 10';

 

I want to take this string and use it as an expression, and get a Decimal value.  Is this possible?  How would I do this?

Bhawani SharmaBhawani Sharma

use this :

 

 

String exp = '25.4 + 10';
List<String> lstStr = exp.split('\\+');
System.debug(lstStr);
System.debug(Double.valueOf(lstStr[0]) + Double.valueOf(lstStr[1]) );

qsdunnqsdunn

Firstly, how complicated will expressions get? Will they always be of the form "value1 operator value2" or can there be nested expressions?

You could use the string methods "indexOf" and "lastIndexOf" to match parentheses, then use "substring" to pluck out the terms inside the parentheses, then use recursive calls to evaluate those.

 

Secondly, you say that the string "contains" the expression; does that mean that there will be other, non-relevant characters in the string? So you might get a string saying "The question is: What is 6x9?" and you want code to strip away all of the letters and non-symbolic puntuation to leave "6x9" then evaluate that to 54?

Or will the string consist only of the expression?

 

Because doing that kind of processing with only the Apex String methods looks like it could be a fair bit of hassle...

Ankit AroraAnkit Arora

Hi Kevin,

 

In addition to Bhawani's reply if your expression can be complex i.e. not only with + sign then you must use delimiters to separate your first value , second value and operator between them eg :

 

String exp = '25.4 @#$ + %^& 10'

 

Now you can split without any chances of facing any issue

 

Thanks

Ankit Arora

Blog | Facebook | Blog Page

kevoharakevohara

Thanks this is helpful.  We are working on a solution to address complex expressions and we seem to have some of it working now.