Strange results with currency value / constant value comparison
compare, delphi, delphi-2009
Solution
As fas as hard casting like Currency(1.32) is not possible, you could use the following for explicit casting
Function ToCurrency(d:Double):Currency;
begin
Result := d;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
C: Currency;
begin
C := 1.32;
if C < ToCurrency(1.32) then
begin
Writeln ('strange');
end;
end;
another way could by forcing the usage of curreny by usage of a const or variable
const
comp:Currency=1.32;
var
C: Currency;
begin
C := 1.32;
if C < comp then
begin
writeln ('strange');
end;
end;
Problem
When compiled with Delphi 2009 and run, this console application writes "strange". The values on both sides of the "less than" operator are equal, but the code behaves as if they are not equal. What can I do to avoid this problem? ``` program Project5; {$APPTYPE CONSOLE} var C: Currency; begin C := 1.32; if C < 1.32 then begin WriteLn('strange'); end; ReadLn; end. ``` p.s. code works fine with other values. This answer by Barry Kelly explains that the Currency type "is not susceptible to precision issues in the same way that floating point code is."