whats new ¦  programming tips ¦  indy articles ¦  intraweb articles ¦  informations ¦  links ¦  interviews
 misc ¦  tutorials ¦  Add&Win Game

Tips (1541)

Database (90)
Files (137)
Forms (107)
Graphic (114)
IDE (21)
Indy (5)
Internet / LAN (130)
IntraWeb (0)
Math (76)
Misc (126)
Multimedia (45)
Objects/
ActiveX (51)

OpenTools API (3)
Printing (35)
Strings (83)
System (266)
VCL (242)

Top15

Tips sort by
component


Search Tip

Add new Tip

Add&Win Game

Advertising

35 Visitors Online


 
...calculate simple arithmetical expressions?
Autor: Thomas Stutz
[ Print tip ]  

Tip Rating (30):  
     


function Calculate(SMyExpression: string; digits: Byte): string;
  // Calculate a simple expression
  // Supported are:  Real Numbers, parenthesis
var
  
z: Char;
  ipos: Integer;

  function StrToReal(chaine: string): Real;
  var
    
r: Real;
    Pos: Integer;
  begin
    
Val(chaine, r, Pos);
    if Pos > 0 then Val(Copy(chaine, 1, Pos - 1), r, Pos);
    Result := r;
  end;

  function RealToStr(inreal: Extended; digits: Byte): string;
  var
    
S: string;
  begin
    
Str(inreal: 0: digits, S);
    realToStr := S;
  end;

  procedure NextChar;
  var
    
s: string;
  begin
    if 
ipos > Length(SMyExpression) then
    begin
      
z := #9;
      Exit;
    end
    else
    begin
      
s := Copy(SMyExpression, ipos, 1);
      z := s[1];
      Inc(ipos);
    end;
    if z = ' ' then nextchar;
  end;

  function Expression: Real;
  var
    
w: Real;

    function Factor: Real;
    var
      
ws: string;
    begin
      
Nextchar;
      if in ['0'..'9'] then
      begin
        
ws := '';
        repeat
          
ws := ws + z;
          nextchar
        until not (z in ['0'..'9', '.']);
        Factor := StrToReal(ws);
      end
      else if 
z = '(' then
      begin
        
Factor := Expression;
        nextchar
      end
      else if 
z = '+' then Factor := +Factor
      else if Z = '-' then Factor := -Factor;
    end;

    function Term: Real;
    var
      
W: Real;
    begin
      
W := Factor;
      while in ['*', '/'] do
        if 
z = '*' then w := w * Factor
      else
        
w := w / Factor;
      Term := w;
    end;
  begin
    
w := term;
    while in ['+', '-'] do
      if 
z = '+' then w := w + term
    else
      
w := w - term;
    Expression := w;
  end;
begin
  
ipos   := 1;
  Result := RealToStr(Expression, digits);
end;


procedure TForm1.Button1Click(Sender: TObject);
var
  
sMyExpression: string;
begin
  
sMyExpression := '12.5*6+18/3.2+2*(5-6.23)';
  ShowMessage(sMyExpression + ' = ' + Calculate(sMyExpression, 3));
end;

 

Rate this tip:

poor
very good


Copyright © by SwissDelphiCenter.ch
All trademarks are the sole property of their respective owners