2

I have an array of strings containing integer numbers. I need to convert them into integers where possible.

Therefore I do like:

if not TryStrToInt ( grid.Cells[columnIndex, i], integerValue ) then begin
  errorsCount := errorsCount + 1;
  errMemo.Lines.Add ( 'Column  "' + fstColumn.Name + '" Line ' + IntTostr ( i ) + ' Value "' + grid.Cells[columnIndex, i] + '" must be integer.' );
end
else begin
   {deal with integerValue}
end;

But when TryStrToInt faces number like '10.0', '11.00' etc, which actually an Integer, it returns false which proceeds error. TryStrToInt in SysUtils.pas implemented as:

function TryStrToInt(const S: string; out Value: Integer): Boolean;
var
  E: Integer;
begin
  Val(S, Value, E);
  Result := E = 0;
end;

As any other string-number convertions it uses Val.

I see only one bad solution like try to convert string to float and then, if successfully, convert float to integer. But it seems ugly. Is there any other standard way? May be not using Val.

UPD: I use Delphi XE5.

9
  • 2
    10.0 is not an Integer. You might want to use TryStrToFloat or parse the string yourself. it not that difficult. Commented Oct 2, 2017 at 10:05
  • @kobik , thank you, but it's ugly way I wrote about. I'm looking for graceful solution. Commented Oct 2, 2017 at 10:06
  • 1
    In such case the only approach is to get float value and analyze it's fractional part. Are you expecting some magic function? Commented Oct 2, 2017 at 10:51
  • 1
    Well, use Frac function to check if it's zero. what is "ugly" about this? doesn't php intval returns 10 for 10.5? Commented Oct 2, 2017 at 11:26
  • 3
    It is about time that you tell us what you consider a graceful solution Commented Oct 2, 2017 at 11:53

1 Answer 1

9

If you require that only numbers with fractional part of zero to be valid Integers you could try this:

function MyStrToInt(const S: string; out Value: Integer): Boolean;
var
  E: Integer;
  RealValue: Real;
begin
  Val(S, RealValue, E);
  Result := (E = 0) and (Frac(RealValue) = 0);
  if Result then Value := Trunc(RealValue);
end;
Sign up to request clarification or add additional context in comments.

2 Comments

Instead of =0 you should use Math.IsZero because there will be some decimal numbers which cannot be represented in binary for which Frac will be <> 0 by a small margin.
@dummzeuch, Thanks. I'll leave that to the OP if he wishes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.