Mega Code Archive

 
Categories / Delphi / Examples
 

A atof() replacement

Title: A atof() replacement Question: How to avoid a exception (EConvertError) when using StrToFloat. Different countries have differnt decimal separators: e.g. ',' - Germany '.' - USA this code works without throwing a exception: var x : Double; begin x := atof('3,1415); // decimal separator: comma x := atof('9.81'); // decimal separator: dot x := atof(' '); // x is 0.0 end; Answer: function atof(s:string) : Extended; var pos_sep : integer; begin s := Trim(s); // remove leading and trailing blanks if s = '' then Result := 0.0 else begin pos_sep := Pos('.', s); if pos_sep = 0 then pos_sep := Pos(',', s); if pos_sep 0 then s[pos_sep] := DecimalSeparator; Result := StrToFloat(s); end; end;