Search code examples
delphidelphi-xe5

delphi xe5 StrToFloat failure changing ThousandSeparator to ','


What am I doing wrong here? I simply want to convert a formatted string to a double and using the TFormatSettings passed in as a parameter to StrToFloat. I get the following exception:

  '3,332.1' is not a valid floating point value.  

The thousand separator and decimal separator are the expected values (',' and '.') in TFormatSettings.

procedure TForm2.Button1Click(Sender: TObject);
var
  FS: TFormatSettings; 
  S: String;
  V: double;
begin
  FS:= TFormatSettings.Create; 
  codesite.Send('ThousandSeparator', FS.ThousandSeparator);  //correct ','
  codesite.Send('DecimalSeparator', FS.DecimalSeparator);    //correct '.'
  S := '3,332.1';
  try
    V := StrToFloat(S, FS);
  except on E: Exception do
    ShowMessage(e.Message);
  end;
  CodeSite.Send('S', S);
  CodeSite.Send('V', V);
end;

Solution

  • What you are doing here is correct, but you stumbled in what it seems a bug(if not a bug at least a not very consistent behaviour) of the TextToFloat(it seems that it ignores ThousandSeparator) internal function of Delphi SysUtils unit(take a look at the Q92265 to follow resolution ) ...

    As a workaround you can try removing the group separator, in this way :

    StringReplace('3,332.1', ',', '', [rfReplaceAll])