Evaluating String Formulas

I was wondering if anyone knew of a library or methods in existing J2SE API that would allow me to evaluate a string formula to a double.
For example, if I had the following code:
Double test;
String formula = new String("12.5 + 15 * 4");
/* What can I do here to make this work */
test = new Double(formula);This would result in a NumberFormatException, because the Double constructor can't resolve the string to a double value.
Anyone have an idea of how to solve this without building my own extensive method with StringTokenizer, etc.
Thanks in advance.

Unfortunately, the formula is entered by a user in a configuration file and stored as a string to start.
The reason is that the user doesn't actually put the values in, rather markers for fields from a database. My application replaces these markers with the actual values. And that is why it is in String format.

Similar Messages

  • How to execute a string formula and assign the result to a number field

    How to execute a string formula and assign the result to a number field
    Hi,
    we have a function that returns a string like this:
    '(45+22)*78/23'
    After we should calculate this string and assign the value to a numeric block field
    Example:
    k number(16,3);
    k:=fun1('(45+22)*78/23'); where fun1 execute and translate to number the string.
    Does exist a function like fun1 ??
    How can we do ?
    Regards

    Hello,
    this is the code that does the job:
    SQL> set serveroutput on
    SQL> DECLARE
    2 ch VARCHAR2(20) :='22+10' ;
    3 i NUMBER ;
    4 BEGIN
    5 EXECUTE IMMEDIATE 'select ' || ch || ' from dual' INTO i;
    6 dbms_output.put_line ('i = ' || TO_CHAR(i));
    7 END ;
    8 /
    i = 32
    Procédure PL/SQL terminée avec succès.
    SQL>
    just you have to do is to create a small stored function that take the string to calculate and return the number result
    Francois

  • CF10 is evaluating strings with comma's as complex types (Array), formerly they were just Strings

    Coldfusion 10's behaviour appears to have changed in the evaluation of strings with commas.
    Example:
    FORM.IDS = 123456, 654321, 789101  (Form Submission)
    <cfset fieldname="IDS" />
    <cfset test1 = FORM[fieldname] />
    <cfset test2 = evalute("FORM.#fieldname#") />
    In Coldfusion 9 the value of test1 and test2 is reported as "123456, 654321, 789101".
    In Coldfusion 10 the value of test1 and test2 is reported as an array. "Array (3)".
    Is this expected behaviour?  This is jacking up an application we are trying to upgrade and did not expect this one.  Any help will be much appreciated.
    Cheers
    Lee 

    ldavis101 wrote:
    Coldfusion 10's behaviour appears to have changed in the evaluation of strings with commas.
    Example:
    FORM.IDS = 123456, 654321, 789101  (Form Submission)
    <cfset fieldname="IDS" />
    <cfset test1 = FORM[fieldname] />
    <cfset test2 = evaluate("FORM.#fieldname#") /> [BKBK: typo corrected]
    In Coldfusion 9 the value of test1 and test2 is reported as "123456, 654321, 789101".
    In Coldfusion 10 the value of test1 and test2 is reported as an array. "Array (3)".
    Is this expected behaviour? 
    No, that is unexpected. Please report it as a bug.

  • Can you really use Display String formula to test for NULL

    I am trying to manipulate the Display String of a field throught the Format Editor.  If a field is null, it should display "N/A", or "No data given", or anything else appropriate I might choose.
    I can't get this feature to work and I'm wondering if there's a bug here.  I'm using the following formula:
    if (isnull() or    trim() = "")
    then "N/A"
        else
    Am I doing something wrong or is there a better way to do this?

    Hi Adriane
    The other way to display "N/A", or "No data given" if a field is null is using a formula with if -else statement as follows:
    whileprinting records;
    if (isnull() or trim () =" ")
    then "N/A"
    else
    Please let me know if this helps.
    Thanks
    Poonam Thorat

  • Group by day - evaluation date formula question

    Hello,
    I am currently working on a report for on-call coverage.  I am having difficulty grouping by date and I'm hoping someone can help me.  Here is my situation.
    The on-call database has a coverage start date and coverage end date.
    Person A has a coverage start date of 9/1/2009 and a coverage end date of 10/5/2009.
    Person B has a coverage start date of 9/15/2009 and a coverage end date of 10/10/2009.
    The report I am trying to create needs to be grouped by the calendar day of coverage.  What I mean is, I need to be able to evaluate the coverage for a particular day.
    If I run the report for the evaluation date of 9/10/2009, it would show Person A, their coverage start date and coverage end date.
    If I run the report for the evaluation date of 9/20/2009, it would show Person A and Person B, with their respective coverage start and end dates.
    My question is, how do I create this evaluation date?
    Since this is a report for on-call coverage, I will also need to run this evaluation date into the future to confirm that there aren't any gaps in coverage.
    What I need to do is run this report for so the evaluation date would be for the next month.  So if I ran the report today, it would show me the on call coverage for November 2009, grouped by day.
    Any help you can provide would be greatly appreciated.

    You will need a calendar-type table, with one record per date.  Then, base your report on something like (MS SQL):
    select calendar.date, on-call.name
    from calendar, on-call
    where calendar.date between '{?lowDate}' and '{?highDate}'
    and calendar.date between on-call.start_date and on-call.end_date
    The first condition of the Where clause selects all of the dates that you want to report.  The second selects each person on-call for each of the dates from the calendar.
    You could also code a loop in the SQL Command, but calendar tables are really quite handy.  (For example, to indicate what dates are company holidays, where no on needs to be on call...)  I'd suggest setting one up if you don't have one available.
    HTH,
    Carl

  • Evaluating strings as literals

    Is there an easy way to evaluate a string like "myVar.property.value <= myOtherVar.property.value" against run-time literal values? The format will always be the same,  but breaking it into 3 parts, running a switch...case through all the operators then trying to convert the strings seems awful cumbersome....

    I have a demo here you might find useful
    MyClass.as
    package 
        import flash.text.TextField;
        public class MyClass
            public var tf:TextField;
            public function MyClass()
                tf = new TextField();
                tf.text = "somthing or other";
    and
    package
        import flash.display.Sprite;
        import flash.events.Event;
        [SWF(backgroundColor="#ffffff", width=400, height=400, frameRate=60)]
        public class Main extends Sprite
            public function Main()
                if (stage)
                    init();
                else
                    addEventListener(Event.ADDED_TO_STAGE, init);
            public function init(event:Event=null):void
                removeEventListener(Event.ADDED_TO_STAGE, init);
                var myClass:MyClass = new MyClass();
                var string:String = "tf.text.length";
                var values:Array = string.split(".");
                trace(myClass[values[0]][values[1]][values[2]]);
    I can't currently think of a way to get hold of the myClass instance though

  • Evaluations array formulas are incorrect (!/?)

    Hi!
    I'm working on a spreadsheet to return MULTIPLE corresponding values for ONE Lookup Value.
    Consider the table array ("A2:C14"), in which you want to lookup the value "A" in column A which has multiple occurrences, and return all corresponding values in column C.
    The complete formula is not the issue.
    I know and have used it in Excel. It's woks in Excel.
    The problem is that Numbers has returned inconsistent results in portion of the formula.
    The entire formula would be =INDEX($C$2:$C$14, SMALL(IF($B$2=$A$2:$A$14, ROW($A$2:$A$14)-ROW($A$2)+1), ROW(1:1)))
    Formula Part =IF($B$2=$A$2:$A$14, ROW($A$2:$A$14)) would evaluates to: {2, FALSE, FALSE, 5, FALSE, FALSE, 8, 9, FALSE, 11, FALSE, 13, FALSE}, wherein the numbers 2,5,8,9,11,13 indicate the worksheet row numbers containing "A".
    However, The following value is returned:
    {2,FALSE,FALSE,2,FALSE,FALSE,2,2,FALSE,2,FALSE,2,FALSE}!
    Note the results of ROW($A$2:$A$14)): {2,2,2,2,2,2,2,2,2,2,2,2,2}. What's happened to the ROW Function?
    The formula results should be {2,3,4,5,6,7,8,9,10,11,12,13}!
    Is not the ROW Function in Numbers an array function?
    I'm using Numbers 3.0 and OSX 10.9

    Sorry, it's not help.
    Numbers 3.0 supports array functions.
    From http://help.apple.com/functions/mac/4.0/#ffa59b4edb
    INDEX
    The INDEX function returns the value in the cell located at the intersection of the specified row and column within a collection of cells or from an array returned by an array function.
    "array function
    Here are some examples of array functions:
    =FREQUENCY($A$1:$F$5,$B$8:$E$8) returns an array of values, based on specified intervals.
    =INDEX(FREQUENCY($A$1:$F$5,$B$8:$E$8),5) would return the fifth value in the array returned by the FREQUENCY function.
    =TRANSPOSE($A$1:$E$3) returns an array containing the transposed values in the array $A$1:$E$3."
    I questioned the result of the function ROW.  Is there a bug or simple limitation?

  • "Eval Parsed Formula Node VI" does not return outputs in predefined order

    I make a data analysis program, where the data consists of some million events and each event has e.g. 4 channels and 1-5 hits on each channel. 
    I would like the user to select different expressions of these channels to give coordinates to plot in a 2D histogram (increment a bin in Intensity Graph), e.g. for some experiment you want to show x=ch1-ch2; y=ch1+ch2+ch3+ch4; while in another experiment you want x=ch1-123; y=123-ch2;
    There are other VIs that use static LabView-code for the normal things, but now after a few years of adding to this program I find that it would be quite good with a general plotter and let the user specify simple expressions like this. Also with the "normal" static plots, there is a need to filter out bad data and then it would be much simpler both to program and use if you could write text expressions with boolean logic to combine multiple filters. Making a LabView code and GUI that allows AND/OR/parenthesis combinations of expressions will be quite an effort and not very reusable.
    So, with the above motivation, I hope you see that it would make sense to have a useable string formula evaluator in LabView. I find some info about MathScript's user-defineable functions, but haven't managed to get MathScript working in LV2010 yet (maybe some licensing or installation issues, I think I had it in 8.6). But I think it would be possible to do most of what I want for the display-part (not the filtering) with the simpler Eval/Parse Formula Node VIs and suitable use of the limited variable name space. So I started testing, and found a quite annoying issue with how the evaulator works.
    To the parser, you are expected to send an array of output variable names. But then it ignores this array, and returns one output per assignment/semicolon in the formula, in the order of the formula text. Since the static parts of my program need to know what the output values mean (which of them is x and which is y), I would have to rely on the user not using any intermediate variable and defining x before y. The attached screenshot demonstrates the problem, and also that it has been solved by NI statff in the "Eval Formula Node VI" which does the appropriate array-searching to extract only the pre-defined outputs, in their expected order. But using that VI is about 100 times as slow, I need to pre-compile the formula and then only use the evaulator in the loop that runs over a million events.
    I don't know if I'll take the time to make my own tweks to the parsing stage (e.g. preparation of array-mapping to not have to repeat the search or maybe hacking the output list generated by the parser) or if I'll have to make it in a static Formula Node in the block-diagram (which supports more functions), so that the user has to run with development environment and stop the program to change the plotting function. But I wanted to share this trouble with you, in hope of improvments in future LabView versions or ideas from other people on how I could accomplish my aim. I have MATLAB-formula node possibility too, but is far as I have seen the only place the user could update the formula would then be in a separate .m file, which is re-read only when typing "clear functions" in the Matlab console window. (Having this window is also an annoyance, and perhaps the performance of calling Matlab in every iteration is not great.) 
    Besides this issue, it also seems very strange there is virtually no support for conditional expressions or operators in Formula Node evaulated formulas (called Mathematics VIs in the documentation). Maybe using (1+sign(a-b))/2 you can build something that is 0 when a<b and 1 when a>b, but it is not user friendly! Would it really be diffcult to add a function like iif(condition, return_value_if_true, return_value_if_false) to replace the unsupported "condition ? if_true : if_false" operator? Would it really be difficult to add support for the < <= >= > == || && operators? Although compiled to an assemply language, this can't exactly be difficult for a CPU.
    Attachments:
    LV script test.png ‏62 KB
    LV script test.vi ‏18 KB

    (1) You can put any kind of code inside an event structure with the limitation that it should be able to complete quickly and without user interaction.  For example a while loop for a newton-raphson method is fine, but an interactive while loop where the stop condition depends on user iteraction is not recommended. By default, event structures lock the front panel until the event completes, so you would not even be able to stop it.
    (2) Yes, you can do all that. LabVIEW has no limitation as a programming language. Use shift registers to hold data and state information, the manipulate the contents as needed.
    (3) I would recommend to use plain LabVIEW primitives instead of formula nodes. Show us your code so we can better see what it's all about. Obviously you have a mismatch betweeen scalars and arrays. It is impossible from the given information where the problem is.
    (4) Yes, look inside the nonlinear curve fit VI (you can open it an inspect the code!). One of the subVIs does exactly that. Just supply your model VI.
    LabVIEW Champion . Do more with less code and in less time .

  • Diffrent Data Type & Formula in Cross Tab

    Post Author: ade
    CA Forum: General
    I using crystal reports 8.5. I make cross tab like this to viewing reportsSubject           Evaluation Aspect                          Score1        Score2            Score3        Score4        Score5 Math               Conceptual Understanding                     80                    75                     70                 80                   A                          Problem Solving                                          77                    80                            90                67                    BEnglish                Reading                                                        89                    80                             86                80                    A                                Wring                                                        80                        80                              70                85                  Bfrom the table above, there are 2 types of different data they are numeric and string.In the using of logical "if" in cross tab is not allowed to use different data type and I don't understand on it... would you please help me, what shoul I do then? 

    Yes it is possible.
    It would be easier in CR2008  where you have the ability to add Calculated Members.
    In previous versions you would need to create a variable for each year and using the GridRowColumnValue function assign the current value to a variable. You would then need to add a second summary field as a "dummy" summary and in the Display string formula declare the variables and manipulate the values as you like and finally convert the output to string.

  • Custom formula in cross-tab?

    I have a cross-tab like this
                      JAN    FEB    MAR ....... DEC (the 12 months as columns)
    year 2006
       item 01     150    205      300 .......    550
       item 02       80    190      284 ........   620
    year 2007
       item 01      458    235      224 .......... 781
       item 02      154    254      134..........  254  
    year 2008
       item 01       245    154      544           1243
       item 02       524    254      124 .........   924     
    I want to know if is possible to have a formula that take the value of each month and compare with the previous and make a calcule like this...
                      JAN    FEB    MAR ....... DEC (the 12 months as columns)
    year 2006
       item 01     150    205      300 .......    550
       item 02       80    190      284 ........   620
    year 2007
       item 01      458    235      224 .......... 781
                       (205)   (14)
       item 02      154    254      134..........  254  
    year 2008
       item 01       245    154      544           1243
       item 02       524    254      124 .........   924 
    where (205) and   (14) are calculate from:
    (205) = (150 - 458) * 100 / 150 I have to  make this operation for each month takin the values from item 01 from 2006 with the values from item 01 from 2007 and so on
    Edited by: j jara on Jul 22, 2008 2:01 AM

    Yes it is possible.
    It would be easier in CR2008  where you have the ability to add Calculated Members.
    In previous versions you would need to create a variable for each year and using the GridRowColumnValue function assign the current value to a variable. You would then need to add a second summary field as a "dummy" summary and in the Display string formula declare the variables and manipulate the values as you like and finally convert the output to string.

  • How to convert String "(50-10)" to number and get output as 40 as a number.

    Hi,
    I have a string with formula, eg: String formula="(ABC-DEF)";
    I replaced the values of ABC and DEF in the above string now I have formula="(50-10)";
    How can I calculate the above value and get output (40)as a number like int or double.
    Regards
    Alex.
    Edited by: AlexRaju on Dec 8, 2009 10:11 AM

    Values for ABC and DEF are coming from different java collections like HashMap or ArrayList etc. The formulas can be complex which need some string manipulations and atlast I will get a string like "(50-10)" or "(20+(Math.SQRT(25)/Math.Power(2,3)))". Here all the numbers are values for variables like ABC or DEF coming from different hashmaps and arraylists based on different conditions.
    Thanks
    Alex.
    Edited by: AlexRaju on Dec 8, 2009 10:36 AM

  • Use subreport total in formula in main report

    Hi,
    I have a subreport which is a total figure. I just want to muliply this by a number in a field on the main report, can this be done?
    Any help appreciated!

    Symptom
    A report contains a subreport. Data from the subreport is required for calculations in the main report.
    How can you share subreport data with the main report in version 7 (or higher) of the Crystal Reports Designer?
    Resolution
    Shared variables, introduced in Crystal Reports version 7, make it easier to pass values from a subreport to the main report. Using shared variables requires two formulas: one to store the value in a shared variable, the other to retrieve the value from the shared variable.
    The most important thing to remember when using shared variables is that Crystal Reports must first evaluate the formula where the value is stored before evaluating the formula that retrieves the shared variable.
    For example if you want to pass a grand total from the subreport to do a calculation in the main report, follow these steps:
    1. In the subreport, create a formula similar to the one below:
    //@SubFormula
    //Stores the grand total of the
    //{Orders.Order Amount} field
    //in a currency variable called 'myTotal'
    WhilePrintingRecords;
    Shared CurrencyVar myTotal := Sum ({Orders.Order Amount})
    2. Place this formula in your subreport.
    3. In the main report, create a formula that declares the same variable name:
    //@MainFormula
    //Returns the value that was stored
    //in the shared currency variable called
    //myTotal in the subreport
    WhilePrintingRecords;
    Shared CurrencyVar myTotal;
    myTotal
    4. Place @MainFormula in a main report section that is beneath the section containing the subreport.
    NOTE:======
    For the shared variable to return the correct value in the main report, you must place @MainFormula in a main report section that is beneath the section containing the subreport. This ensures Crystal Reports evaluates the @SubFormula before @MainFormula.
    One way to do this is to insert a section below the section containing the subreport, and place @MainFormula in this new sub-section:
    · On the 'Format' menu, click 'Section'.
    · On the 'Sections' list, click the section containing the subreport.
    · Click 'Insert' (at top of dialog box). This inserts an additional subsection.
    · Click 'OK' to return to the report, and insert @MainFormula into this new sub-section.
    The next time you preview the report, @MainFormula displays the value from the subreport. In this particular example, that value was the grand total of the {Orders.Order Amount} field.
    ============
    5. Once you have verified that @MainFormula is returning the correct value from the subreport, you can include this formula in other main report formulas, such as:
    //@NewFormula
    //includes data from subreport
    {@MainFormula}+ Sum ({Customer.Last Year's Sales})
    · Place this formula in the same section as @MainFormula, or in a section further down on the report.
    You have now successfully shared data from a subreport with the main report.
    NOTE: =====
    This is not possible with On Demand Subreports in Crystal Reports.

  • Parsing Boolean Formula

    Hey guys, i'm having some trouble with a program i've been working on. Im a bit of a newbie so do forgive me if I seem as though i'm being a bit thick. I'm trying to split a boolean formula into it's sub formulas and parse the results into an array. For example, with the formula a&(a&b) i would have 'a' and 'a&b' store in the array and with the formula a&(a&b)&(b&c) I would have 'a', 'a&b' and 'b&c' I've been trying at it for a while now but don't seem to be getting anywhere. Code I have so far is:
    import java.io.*;
    public class ReadString
         public static void main (String[] args)
              String[][] myArray = new String[40][4];
              System.out.print("Please enter a formula: ");
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              String inputtedFormula = null;
              try
                   inputtedFormula = br.readLine();
              catch (IOException ioe)
                   System.out.println("IO error trying to read your formula!");
                   System.exit(1);
              myArray[0][0] = inputtedFormula;
              Loopy(myArray);
         public static void Loopy (String myArray[][])
              int countStart = 0;
              int countEnd = 0;
              String formula = myArray[0][0];
              int stringLength = formula.length();
              int stringPosition = stringLength;
              for(;stringPosition>=0;stringPosition--)
    I know I need to run through the formula and keep track of open and closed brackets and also keep track of start and end positions of these brackets so the code knows which sections to parse separately but I just can't figure it out and pretty much feel like i've hit a brick wall. Any help will be much appreciated.

    How very helpful, thanks for that. I have been researching but so far everything i've found is either too rigid or not complex enough. I've tried using stringTokenizer and streamTokenizer but couldn't get the results i needed. All i could do was remove the brackets and take what's between but i need the program to recognise the operators and i don't really know how to do this

  • Display String in cross tab in place of blank cell

    Hi,
    I am using CR 2008  and my issue is when i run crosstab i am getting a blank values fro some data becuase which that criteria there is no data in Database . I need to display a string in that area. How can I achieve this?

    Hi Venkat,
    There is a Display String formula for fields, accessed by right-clicking the field and selecting Format Field.  This is used to tell Crystal exactly what should be displayed for the field.  Add the following logic (basic syntax):
    if CurrentFieldValue = 0 then
      formula = "your display srting"
    else
      formula = cstr(CurrentFieldValue, "0.00")
    end if
    This will cause all zero values to display as blank.  I added the "0.00" parameter to the cstr() function to show that's how you tell cstr() how you want the number formatted.  See the online help for cstr() for details.
    --Naga.

  • Problem building a formula

    I am building a complex formula and the tools don't seem to allow what I need to do.
    My code is
    [Code]
    Local StringVar vTest1 := Trim ({PURCHORDER.L_INDEX});
    if length(vTest1) >= 1 then
      Local StringVar docType := {L_HPCR.OBJECT}[6 To 6];
      Local StringVar Comment1 := {L_HPCR.OBJECT}[95 To 256];
      If docType In ["P", "p"]
      and ({PURCHORDER.L_INDEX} = {L_HPCR.L_INDEX})Then
        Comment1
      Else
        "no type P comment"
    else
      "no comment"
    [/Code]
    The problem is that there are docTypes of D and P. The returned value is D - then next record is P.
    I really would like to loop through 5 records while the L_INDEX values are equal.
    Does anybody have an idea how to do this???
    Edited by: jcarrott on Jan 18, 2010 10:25 PM
    The PO comments are of several types, The first part of the L_HPCR.OBJECT field is 'TYPE=' . This comment has 2 types a D and a P. The L_INDEX is the same for both. The code above only finds the the first comment (type=D), so the message that prints on the PO is "no type P comment" when in fact there is one. I really want the record where docType is = to P and the indexes are equal. I can't seem to get that condition to work.

    1.  Using Group Expert, add a group on the index field.  Then you will have formats for Group 1 Header, Details, and Group 1 Footer (assuming this is the only group, which, if you don't know what groups are, is probably the case :->).
    2.  Create a formula field like the one below (in #4).  Place it on the Detail format.  Make sure the formula has WhilePrintingRecords at the top.  This will need to use a shared variable (which I'll call CommentText), described more fully below.
    3.  Since the new group is only so you can look at all of the records for a group prior to printing the comments, create another formula field to get the CommentText shared variable (basic syntax):
    WhilePrintingRecords
    shared CommentText as string
    formula = CommentText
    CommentText = ""   ' reset the value of the comment for next index.
    Place this in the group footer where you want to print the comments.
    4.  A shared variable will keep its value between reading records, so your formula will need to look something like (basic syntax):
    WhilePrintingRecords
    shared CommentText as string
    dim docType as string
    dim comment1 as string
    if length(Trim ({PURCHORDER.L_INDEX})) >= 1 then
      docType = {L_HPCR.OBJECT}[6 To 6]
      comment1 = {L_HPCR.OBJECT}[95 To 256]
      If docType In [\"P\", \"p\"]
         and ({PURCHORDER.L_INDEX} = {L_HPCR.L_INDEX})Then
          CommentText = CommentText + Comment1  ' concatenate all comments if more than 1 P rec
      end if
    end if
    formula = ""
    HTH,
    Carl

Maybe you are looking for