Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

x.xxxx is not a valid floating point. Converting between languages/locals

I have a spanish user who is getting an invalid floating point error when doing this

var
  S : String;
  R : Real;
begin
  S := '3.12345';
  R := StrToFloat(S); //- Exception here.

The reason for this is that his location uses , for the decimal place!
How can I safely convert the string above to a float for the user without it bombing out.

like image 708
Wizzard Avatar asked May 01 '11 21:05

Wizzard


4 Answers

Roll your own version of StrToFloat

function StrToFloat_UK(const AStr: string): Float;
var
  FS: TFormatSettings;
begin
  FS.Create('en-UK');
  Result:= StrToFloat(AStr, FS): 
end;

And use this in place of StrToFloat.

like image 116
Johan Avatar answered Nov 01 '22 09:11

Johan


Use the second overload of StrToFloat with a TFormatSettings that has DecimalSeparator set to ..

like image 23
Joey Avatar answered Nov 01 '22 09:11

Joey


You could use the procedure val, it disregards local system settings.

var
S : String;
R : Real;
Test: Integer;
begin
  S := '3.12345';
  Val(S, R, Test);
end;
like image 28
MGH Avatar answered Nov 01 '22 09:11

MGH


If you know that the strings use . as the decimal separator, then you should do something like

procedure TForm1.FormCreate(Sender: TObject);
begin
  Application.UpdateFormatSettings := false;
  DecimalSeparator := '.';
end;

The line

Application.UpdateFormatSettings := false;

is very important. The default value of this property is true, and in such case, the DecimalSeparator variable may be reverted to its default value (e.g. ,) anytime, for instance when you switch user.

like image 1
Andreas Rejbrand Avatar answered Nov 01 '22 09:11

Andreas Rejbrand