How to calculate % change from X to Y in Pascal

1 Answer

0 votes
program PercentChangeProgram;

{$mode objfpc}

uses
  SysUtils, Math;

function percentChange(x, y: Double): Double;
begin
  Result := ((y - x) / Abs(x)) * 100.0;
end;

function describeChange(x, y: Double): String;
var
  pct: Double;
begin
  pct := percentChange(x, y);

  if pct > 0 then
    Result := Format('From %.1f to %.1f is a %.2f%% increase (+%.2f%%)',
                     [x, y, pct, pct])
  else if pct < 0 then
    Result := Format('From %.1f to %.1f is a %.2f%% decrease (%.2f%%)',
                     [x, y, Abs(pct), pct])
  else
    Result := Format('From %.1f to %.1f is no change', [x, y]);
end;

begin
  Writeln(describeChange(-80.0, 120.0));
  Writeln(describeChange(120.0, 30.0));
end.



(* 
run:

From -80.0 to 120.0 is a 250.00% increase (+250.00%)
From 120.0 to 30.0 is a 75.00% decrease (-75.00%)

*)

 



answered May 29 by avibootz
edited May 29 by avibootz
...