strtofloat的小问题,请各位高手指教(50分)

  • 主题发起人 touchnet
  • 开始时间
T

touchnet

Unregistered / Unconfirmed
GUEST, unregistred user!
大家好,我用strtofloat()转换时发现有时小数点后会出现很多位,请问有什么方法能够解决
小数点后只有两位(需要将后面的四舍五入)。还有,为什么string的转换后就多出很多位,
请指教,谢谢!
 
1. 可以用Format函数: Caption:=Format('%.2f',[3/2.1]);
2. 这是因为浮点数在机器内是用有限长度的2进制数存放的,所以不可避免的会有一些误差。
 
var d:string;
begin
d:='1.2';
showmessage(floattostr(strtofloat(d))+'end');
end;
结果1.2end 并没有出现你说的问题啊?!
小数点的位数可通过format函数解决
 
谢谢各位大虾,Format函数能把小数点两位后的数字四舍五入吗,请给个小例子,谢谢!
 
procedure TForm1.Button2Click(Sender: TObject);
var

S, T: string;

begin

Str(1.4:2:1, T);
S := T + ' rounds to ' + IntToStr(Round(1.4)) + #13#10;
Str(1.5:2:1, T);
S := S + T + ' rounds to ' + IntToStr(Round(1.5)) + #13#10;
Str(-1.4:2:1, T);
S := S + T + ' rounds to ' + IntToStr(Round(-1.4)) + #13#10;
Str(-1.5:2:1, T);
S := S + T + ' rounds to ' + IntToStr(Round(-1.5));
MessageDlg(S, mtInformation, [mbOk], 0);

end;

dephi自带的例子希望能帮你:)
 
nj_wangzhen你好,我在对文本的处理中,将一些字段读入到string中,然后strtofloat,对若干
个字段加乘处理,得到一个数值,然后floattostr();richedit1.lines.add('floattostr()');
就出现了小数点后很多位,这种情况有时又不会出现,让我很奇怪。
 
具体原因我不是很知道,但不是有format函数吗,在适当的时候做个转换就行了
而且我的第一个例子也说了没出现你的那种情况
 
richedit1.lines.add('floattostr()');
改为:richedit1.lines.add(floattostr());
 
使用 Format or str
 
谢谢各位!
 
多人接受答案了。
 
顶部