Reputation:
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..
Upvotes: 2
Views: 5516
Reputation: 8406
The problem with this question is that saying "is too slow" doesn't tell much. What does the profiler tells to you? Do you have an informed idea about the input data? What about different notations, for example, 6.02e23
?
If your input data is mostly noise, then using regular expressions (as answered here) may improve things but only as a first filter. You could then add a second step to actually obtain your number, as explained by David's answer.
Upvotes: 0
Reputation: 81
Can you use a RegEx here? Something like:
([+-]?[0-9]+(?:\.[0-9]*)?)
Upvotes: 2
Reputation: 612963
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
....
Upvotes: 7