How to compare double in delphi?

后端 未结 2 1552
离开以前
离开以前 2020-12-13 19:14

We are facing issue with data type double comparison:

if(p > pmax) then
begin
  Showmessage(\'\');
end

If both values are 100 (p=100 and

2条回答
  •  星月不相逢
    2020-12-13 19:25

    There are several problems with comparing Doubles. One problem is that what you see is not exactly what you get due to rounding. You can have 99.999999996423 and 100.00000000001632, which are both rounded to 100, but they are not equal.

    The solution is to use a margin so that, if the difference of the two Doubles lies within the margin, you accept them as equal.

    You can create an IsEqual function using the margin as an optional parameter:

    function IsEqual(const ANumber1, ANumber2: Double; const AMargin: Double = cMargin): Boolean;
    begin
      Result := Abs(ANumber1-ANumber2) <= AMargin;
    end;
    

提交回复
热议问题