Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a compiler setting to control how floating point literals are typed in Delphi?

While the the case for e works by default I would like to change the default casting of the literal 0.1 to allow the r to work without any code modifications. Is this possible through a compiler option, compiler directive, or anything else?

procedure Test;
var
  s : Single;
  r : Real;
  d : Double;
  e : Extended;
begin
  s := 0.1;
  if (s = 0.1) then ShowMessage('s matched'); // fail

  r := 0.1;
  if (r = 0.1) then ShowMessage('r matched'); // fail

  d := 0.1;
  if (d = 0.1) then ShowMessage('d matched'); // fail

  e := 0.1;
  if (e = 0.1) then ShowMessage('e matched'); // pass
end;
like image 399
user1627960 Avatar asked Jun 01 '18 13:06

user1627960


1 Answers

There is no compiler switch that does what you wish. The issue is that a floating point literal is represented as a 10 byte extended precision value by the 32 bit Windows compiler. And because 0.1 is not exactly representable, that is not equal to the 8 byte double precision representation of 0.1.

The documentation says:

If constantExpression is a real, its type is Extended.

You can however achieve the desired result by using a typed constant. For example:

const 
  TenthDouble: Double = 0.1;
var
  d: Double;
....
d := 0.1;
if d = TenthDouble then
  .... 

By using a typed constant we are able to force the compiler to make the constant be the 8 byte double precision representation of 0.1.

like image 103
David Heffernan Avatar answered Sep 19 '22 08:09

David Heffernan