procedure Str(X [: Width [: Decimals ]]; var S); 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;
function roundEx(num: Float;Wided,decimas : Integer) :Float; var T : string; begin Str(num:Width:decimas , T) //width;整个数据长度,decimas:小数点位数 Result :=Round(StrToFloat(T)); end;
直接用format函数 function MyRound(numb,mystr:string):string; var s:string; begin s:='%0.'+numb+'f'; result:=format(s,[strtofloat(mystr)]); end; 其中numb为小数点后的位数,mystr为数据源,返回为想要的数
RoundTo函数 type TRoundToRange=-37..37; Function RoundTo(const AValue:Double;const ADigit:TRoundToRange):Double;该函数利用银行业舍入法将浮点数四舍五入为指定的阿拉伯数字或10的幂数。AValue参数为待转换的值。ADigit指定要将AValue值四舍五入成的10的幂数,可以是-37到37之间的任何值。 该函数的行为可能受Set8087CW过程或SetRoundMode函数的影响。
round();这是四舍五入
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;
设定小数位数后,类型转换,Round(StrToFloat(T))
var
T : string;
begin
Str(num:Width:decimas , T) //width;整个数据长度,decimas:小数点位数
Result :=Round(StrToFloat(T));
end;
分别试试:round(4.5)和round(5.5)
你会发现round(4.5)返回4,不是我们期望的5
而round(5.5)返回的是6也就是说,对于偶数,round园整(.5)后的结果比正确值小1.
对于奇数是正常的。
这也是Delphi稀奇古怪的BUG之一
RoundTo(1.234, -2) // 小数点后2位具体看帮助
这是一种叫银行家四舍五入方式不是BUG
这不是BUG,是银行家算法,因为它用
FPU进行处理,所以没办法,
这个问题在
PASCAL 精要里有介绍
如果是 Round(奇數.5)=奇數+1
Round(偶數.5)=偶數我再好就就發現這個問題了,但是我一直不知道是什么原因!
对于取小数点多少位之后四舍五入,这样:
trunc(x*a+0.5)/a,这里a为1,10,100等10的n-1次方(n=1,2,3,...)。
所以,你要取0.54663小数点后面3位并四舍五入,就这样:
0.54663*100+0.5=546.63+0.5=547.13,trunc之后时547,然后/100就成为0.547了.
function MyRound(numb,mystr:string):string;
var
s:string;
begin
s:='%0.'+numb+'f';
result:=format(s,[strtofloat(mystr)]);
end;
其中numb为小数点后的位数,mystr为数据源,返回为想要的数
roundto(12.344,-1)=12.3
roundto(12.344)=12roundto(12.345,-2)=12.35
...
一个简单的问题为什么搞这么复杂
比如0.54663四舍五入小数点后的4位
就用
StrToCurr(Format('%100.2f',[0.54663]));这样得到的是精确的数字,小数为的位数和
值都可以动态的写入
SimpleRoundTo(1.234, -2) 1.23
SimpleRoundTo(1.235, -2) 1.24
SimpleRoundTo(-1.235, -2) -1.23
type TRoundToRange=-37..37;
Function RoundTo(const AValue:Double;const ADigit:TRoundToRange):Double;该函数利用银行业舍入法将浮点数四舍五入为指定的阿拉伯数字或10的幂数。AValue参数为待转换的值。ADigit指定要将AValue值四舍五入成的10的幂数,可以是-37到37之间的任何值。
该函数的行为可能受Set8087CW过程或SetRoundMode函数的影响。
var
a:int;
b:float;
a:= b+0.5;
formatfloat('0.00',0.545); //结果 0.55
可以说明是真正的四舍五入。