Mega Code Archive

 
Categories / Delphi / Functions
 

IsFloat function

Title: IsFloat function Question: How do you tell if a string is a valid float? Answer: I was asked the question "How do I know if a string is a float?" Well, I immediately though of StrToFloat. But I hate the idea of raising an exception if it fails and sides I may not want the value just yet. Looking at StrToFloat I realized that I could use TextToFloat instead to tell me if the value is a valid float. My simple example: unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} function IsFloat(S: string): boolean; var f: extended; begin Result := TextToFloat(PChar(S), f, fvExtended); end; procedure TForm1.Button1Click(Sender: TObject); begin if IsFloat(Edit1.text) then Showmessage('Yes') else Showmessage('No'); end; end.