Comparison of variables of different type with conversion returns incorrect result

5

I have the following code

var
  Valor1: string;
  Valor2: Double;
begin
  Valor1 := '150.15';
  Valor2 := 150.15;

  If StrToFloat(Valor1) = Valor2 then
     ShowMessage('Iguais');
end;

In this situation, sometimes Delphi understands that the values are different, but if you use the code below they are considered equal

    var
      Valor1: string;
      Valor2: Double;
  Valor2: Double;
    begin
      Valor1 := '150.15';
      Valor2 := 150.15;
      Valor3 :=  StrToFloat(Valor1);

      If Valor3 = Valor2 then
         ShowMessage('Iguais');
    end;

Note: in the example I am setting the values directly for the variable, however, the problem I had occurred from reading a data from the serial, but even though I used the FormatFloat function this still occurred, and if I gave a debug in the variables the values were equal, and yet they were not considered equal in if

    
asked by anonymous 14.06.2018 / 18:14

2 answers

3

If you are going to use the StrToFloat function consider passing it a string with ',' and not '.' to decimal separator.

Another detail is the Type of Variable that will receive the result.

In System.SysUtils we have:

function StrToFloat(const S: string): Extended;

var
  Valor1: string;
  Valor2: Extended;
begin
  Valor1 := '150,15';
  Valor2 := 150.15;

  If StrToFloat(Valor1) = Valor2 then
     ShowMessage('Iguais');
    
14.06.2018 / 19:08