写了一个函数,出错。帮忙看看。

icank 2003-01-08 01:20:10
function CutFloat(const Value: Extended; const Digits: Byte): Extended;
var
V1, LFactor: Extended;
V2: Int64;
begin
LFactor := IntPower(10, Digits);
V1 := Value * LFactor;
V2 := Trunc(V1);
V1 := V2 / LFactor;
Result := V1;
end;

用 CutFloat(100.51, 5) 调用,返回 100.51 正确。
但用 CutFloat(150.51, 5) 调用,返回的是 150.50999
V2 用的是 Int64 类型,15051000 并没有超出范围啊!怎么回事啊?
应该怎么样修改?
...全文
42 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
lxpbuaa 2003-01-10
  • 打赏
  • 举报
回复
Delphi已经有这个方法了:
procedure Str(X [: Width [: Decimals ]]; var S);
比如:

var
T: string;
begin
Str(100.51:0:5, T);
//T=100.51000
end;

—————————————————————————————————
宠辱不惊,看庭前花开花落,去留无意;毁誉由人,望天上云卷云舒,聚散任风。
—————————————————————————————————
singlesword 2003-01-09
  • 打赏
  • 举报
回复
function CutFloat(const Value: Extended; const Digits: Byte): Extended;
begin
var
Str1, Str2: string;
i, Count: integer;
begin
Str1 := FloatToStr(Value);
i := 1;
Count := -1;
while i<=Length(Str1) do
begin
Str2 := Str2 + Str1[i];
if Count > -1 then
Inc(Count);
if Count = Digits then
break;
if Str1[i] = '.' then
Count := 0;
Inc(i);
end;
Result := StrToFloat(Str2);
end;
singlesword 2003-01-09
  • 打赏
  • 举报
回复
呵呵,那个Temp是多余的,忘了删掉了。
singlesword 2003-01-09
  • 打赏
  • 举报
回复
这样吧?
function CutFloat(const Value: Extended; const Digits: Byte): Extended;
begin
var
Str1, Str2: string;
Temp: Extended;
i, Count: integer;
begin
Temp := IntPower(10, Digits) * Value;
Str1 := FloatToStr(Value);
i := 1;
Count := -1;
while i<Length(Str1) do
begin
Str2 := Str2 + Str1[i];
if Count > -1 then
Inc(Count);
if Count = Digits then
break;
if Str1[i] = '.' then
Count := 0;
Inc(i);
end;
Result := StrToFloat(Str2);
end;
fengjn 2003-01-09
  • 打赏
  • 举报
回复
转成字符串
然后copy
再转回数值
icank 2003-01-08
  • 打赏
  • 举报
回复
那么这个函数应该怎么写呢?

function CutFloat(const Value: Extended; const Digits: Byte): Extended;

截断实数,不舍取。如:
CutFloat(0.99999, 3) = 0.999
hfycl 2003-01-08
  • 打赏
  • 举报
回复
UP
singlesword 2003-01-08
  • 打赏
  • 举报
回复
trunc跟round好像都不行的。
前几天作一个报表时发现。
trunc(1.5)=2
而trunc(2.5)=2
round一样。
返回一个离得最近的偶数:(
swayi21 2003-01-08
  • 打赏
  • 举报
回复
UP
墨梅无痕 2003-01-08
  • 打赏
  • 举报
回复
Trunc()函数在截断一个浮点数时,好像进行了精度控制。
把Trunc()换成Round()函数吧。

16,748

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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