Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if string contains a float?

How can I detect if a string contains a float. For example: '0.004'

But without using StrToFloat because that function are slow but rather by iterating through chars.

function IsInteger(const S: String): Boolean;
var
  P: PChar;
begin
  P := PChar(S);
  Result := True;
  while not (P^ = #0) do
  begin
    case P^ of
      '0'..'9': Inc(P);
    else
      Result := False;
      Break;
    end;
  end;
end;

This will check if string is a positive integer but not a float..


2 Answers

I would use TryStrToFloat():

if TryStrToFloat(str, value, FormatSettings) then
  ....

If you are prepared to use the default system wide format settings then you can omit the final parameter:

if TryStrToFloat(str, value) then
  ....
like image 83
David Heffernan Avatar answered Feb 16 '26 15:02

David Heffernan


Can you use a RegEx here? Something like:

([+-]?[0-9]+(?:\.[0-9]*)?) 
like image 33
user3038458 Avatar answered Feb 16 '26 14:02

user3038458



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!