Forum > General

Using TFPExpressionParser with calculations

(1/1)

Rexpiger:
Hello all,
I am trying to make a calculator in lazarus IDE.
I want to take user input (string) say "1+1+2-3" and i then want to calculate it.Someone suggested i use TFPExpressionParser but, unfortunately Im having a hard time understanding the documentation.Could someone help me out, but me on the right path?

So i can take a string and calculate it and then save the result in a variable to be displayed.

Thanks in advance to anyone kind enough to help :)

Here is what i have so far: ( var test = user input)

procedure TForm1.OpEqualsClick(Sender: TObject);
begin
  //Do the operation
       test:= '1+1';
     FParser := TFPExpressionParser.Create(nil);
     try
        FParser.BuiltIns := [bcMath];
        FParser.Expression := test;
        parserResult := FParser.Evaluate;
        result := FParser.Expression + ' = ' + parserResult;
        output.caption:= result;
     finally
       FParser.Free;
     end;
end;   

wp:
You must convert the parser's result to a string before you can append it to the parser's Expression string. However, since the result can have many types you must use a case instruction to pick the correct conversion function:

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---procedure TForm1.Button1Click(Sender: TObject);var  parser: TFPExpressionParser;  test: String;  parserResult: TFPExpressionResult;  resultString: String;begin  //Do the operation  test:= '1+1';  parser := TFPExpressionParser.Create(nil);  try    parser.BuiltIns := [bcMath];    parser.Expression := test;    parserResult := parser.Evaluate;    case parserResult.ResultType of      rtInteger: resultString := IntToStr(parserResult.ResInteger);      rtFloat: resultString := FloatToStr(parserResult.ResFloat);      rtBoolean: resultString := BoolToStr(parserResult.ResBoolean);      rtDateTime: resultString := DateTimeToStr(parserResult.ResDateTime);      rtString: resultString := parserResult.ResString;    end;    resultString := parser.Expression + ' = ' + resultString;    Caption:= resultString;  finally    parser.Free;  end;end;

Rexpiger:
Thank you so much, I shall have a look as soon as i am back at my pc!!

Navigation

[0] Message Index

Go to full version