请教各位:一个四舍五入的小问题(50分)

  • 主题发起人 Sdelphi_fu
  • 开始时间
S

Sdelphi_fu

Unregistered / Unconfirmed
GUEST, unregistred user!
各位大哥:
你们好,我是一个新手,有一个小问题想请教各位,有一个REAL/FLOAT类型的数值,
用什么function 可以取到它小数点以后的第几位四舍五入的数值?
如下:
var
avalues,x:real;
begin
x := 3.156;
...
avalues := (???) 3.16;
*** 用什么"function",round()/trunc()...如何取到 avalues的值是3。16??
end;

 
round(x*10)/10
 
to zw84611:
你好,如果按你的思路,应该是round(x*100)/100才对,但是如果我要四舍五入到
小数点后的某一位呢?你的这种方法好像有点不好用,能有好一点的方法吗?谢谢!
 
roundto函数
 
to ugvanxk :
你好,有“roundto”这个函数吗?能讲一下如何使用吗?
谢谢!
 
function RoundTo(const AValue: do
uble;
const ADigit: TRoundToRange): do
uble;
Description
Call RoundTo to round AValue to a specified power of ten.
AValue is the value to round.
ADigit indicates the power of ten to which you want AValue rounded. It can be any value from –37 to 37 (inclusive).
RoundTo uses “Banker’s Rounding” to determine how to round values that are exactly midway between the two values that have the desired number of significant digits. This method rounds to an even number in the case that AValue is not nearer to either value.
The following examples illustrate the use of RoundTo:
Expression Value
RoundTo(1234567, 3) 1234000
RoundTo(1.234, -2) 1.23
RoundTo(1.235, -2) 1.24
RoundTo(1.245, -2) 1.24
Note: The behavior of RoundTo can be affected by the Set8087CW procedure or SetRoundMode function.
 
可能要setroundmode([rmnearest]);
roudto 才能合要求,你试一下,我也没试过
 
to ugvanxk :
你好,我现在用的是D5版的,查了一下是没有这个FUNCTION,你用delphi_Vx版的?
我想请教一下:你所讲的RoundTo()是
Delphi本身自带的FUNCTION还是后台数据库所带有的
FUNCTION?
谢谢!
 
來個簡單的:
formatfloat('#,##0.000',yournum);
//三位
formatfloat('#,##0.0000',yournum);
//四位
 
var
avalues,x:real;
begin
x := 3.156;
...
avalues := Trunc((x*100)+0.5)/100;
end;
加个0.5就可以四舍五入,具体位数你可以自己定
 
var
s:string;
avalues,x:real;

begin
x := 3.156;
...
str(x:0:2,s);
avalues:=strtofloat(s);
end;

想保留几位都可以,只要把替换2为欲保留的位数即可;
 
用trunc是正解,round的结果是向偶数靠齐的,不是四舍五入,请参考delphi的手册。
 
自己做一个吧!
procedure MyRound(var x:Real;d:integer);
var
s:string;
begin
try
str(x:20:d,s);
x:=strtofloat(trim(s));
except
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
x:real;
begin
x := 3.156;
showmessage(floattostr(x));
Myround(x,2);
showmessage(floattostr(x));
end;
 
uses math;
function MyRound(x:Double;count:Integer):Double;
begin
result := Trunc((x*Power(10, count))+0.5)/Power(10, count);
end;

//x,原始数值
//count,点后保留位数
 
ShowMessage(FormatFloat('#.0000',1234.56789));
 
to all:
你们好,多谢各位热心指教,问题已解决,下次有问题,请望各位多多关照!
 
多人接受答案了。
 
顶部