字符转换数值型出现的错误

wave_f 2004-06-25 04:14:35
有一些这样的字符串:10cm, 2.5", 8m/m等,想要转成数值型,结果是:10 ,2.5 ,8,我用strtoint语句出现错误,盼高手解决
...全文
101 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
江宁侯哥 2004-06-25
  • 打赏
  • 举报
回复
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,IdGlobal;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function GetNumbystr(str :string) :real;
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

function TForm1.GetNumbystr(str: string): real;//取出字符串开头的数字
var
p : pchar;
i : integer;
c : char;
strVal,strTemp : string;
pos :integer;
begin
strVal := Trim(str);

if Length(strVal)<=0 then
begin
Result := 0;
exit;
end;
pos := length(strVal);
for i := 0 to length(strVal) - 1 do
begin
p := Pchar(strVal);
c := p[i];
if not IsNumeric(c) then
begin
SetLength(strTemp,1);
strTemp :='.';
if strTemp <> c then
begin
pos := i;
break;
end;
end;
end;

Result := strtofloat(copy(strVal,0,pos));

end;

procedure TForm1.Button1Click(Sender: TObject);
var
str :string;
begin
str :='10cm/m';
showmessage(floattostr(GetNumbystr(str)));
end;

end.
pengxuan 2004-06-25
  • 打赏
  • 举报
回复
你的这些字符串里含有非数字字符,转换会现错误,
你需要把非数字字符干掉,再转就OK
juliens 2004-06-25
  • 打赏
  • 举报
回复
你得自己写函数过滤掉这些非法字符才行,除了点号外!
juliens 2004-06-25
  • 打赏
  • 举报
回复
你直接用IntToStr来转换这些字符串当然会出错,因为它们含有非数字字符啊!
fei19790920 2004-06-25
  • 打赏
  • 举报
回复
i:=StrToIntDef(str,0);

5,388

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧