在Delphi中将不寻常的整数字符串转换为整数值
我有一个包含整数的字符串数组。如果可能的话,我需要把它们转换成整数 因此,我喜欢:在Delphi中将不寻常的整数字符串转换为整数值,delphi,Delphi,我有一个包含整数的字符串数组。如果可能的话,我需要把它们转换成整数 因此,我喜欢: if not TryStrToInt ( grid.Cells[columnIndex, i], integerValue ) then begin errorsCount := errorsCount + 1; errMemo.Lines.Add ( 'Column "' + fstColumn.Name + '" Line ' + IntTostr ( i ) + ' Value "' + grid
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;
但当TryStrToInt面对像“10.0”、“11.00”等实际上是整数的数字时,它会返回false,从而导致错误function TryStrToInt(const S: string; out Value: Integer): Boolean;
var
E: Integer;
begin
Val(S, Value, E);
Result := E = 0;
end;
与任何其他字符串数字转换一样,它使用Val
我只看到一个糟糕的解决方案,比如尝试将字符串转换为浮点,然后,如果成功,将浮点转换为整数。但它看起来很丑陋。
还有其他的标准方法吗?可能没有使用Val
UPD:我使用Delphi XE5。如果您要求只有分数部分为零的数字才是有效整数,您可以尝试以下方法:
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;
10.0
不是整数。您可能希望使用TryStrToFloat
或自己解析字符串。“这没那么难。”科比克,谢谢你,但这是我写的难看的方式。我在寻找优雅的解决方案。在这种情况下,唯一的方法是得到浮点值并分析它的分数部分。你期待一些神奇的函数吗?好吧,使用Frac
函数检查它是否为零。这件事的“丑陋”是什么?PHP <代码> InValue<代码>返回< <代码> 10 > <代码> <代码> 10.5 > /代码>现在是时候告诉我们你认为优雅的解决方案而不是= 0,你应该使用Math.IS0,因为会有一些小数,不能用二进制表示,FRAC将用0的小余量来表示。如果他愿意的话,我会把这件事留给检察官。