Home > Back-end >  Comparing float with small integer
Comparing float with small integer

Time:08-19

If I have

f: Single;
F := 0;
if F <> 0 then raise exception.create('xxx');

does this comparison will work fine in any platforms? I mean do I will need to do round(f) <> 0 in some platforms? I know that on Windows doing F <> 0 is fine because 0 is an integer but I m curious for other platforms

CodePudding user response:

In the title, you ask for a general answer, and in the body, you ask for a specific case. I'm not sure which answer you are trully interested in. But as a general case, the answer is "It depends".

As other have commented, your specific example will never raise, but it does not mean it's safe to compare a float to 0.

Take this exemple :

procedure TForm5.Button1Click(Sender: TObject);
var
  F: single;
begin
  F := (7 / 10);
  F := F - 0.7;
  if F <> 0 then
    raise Exception.Create('Error Message');
end;

This will (as far as I know) always raise.

Also, round(f) <> 0 wouldn't be the way to go about this. Comparevalue(F, 0, ????) <> EqualsValue would be.

As to the "why" of all this, this has been answered (probably numerous times) on SO. (you can start here)

  • Related