要自己写函数处理:先在单元uses中加入Math 参数说明: InReal:取整浮点数 Len:小数位数 RoundOrTrunc:0:是四舍五入;1:截断,2: 有小数时向上取整 function RoundReal(InReal: real; Len: integer; RoundOrTrunc: integer=0): real; var I, numb: integer; str: string; begin try numb := 1; for i := 0 to len - 1 do numb := numb * 10; if RoundOrTrunc = 0 then //四舍五入 result := Round(InReal * numb) / numb else if RoundOrTrunc = 1 then //截断 begin Str := FloatToStr(InReal * numb); if pos('.', Str) = 0 then Result := InReal else begin Str := Copy(str, 0, pos('.', Str) - 1); result := StrToFloat(Str) / numb; end; end else //2: 有小数时向上取整,返回一个整数。 result := Ceil(InReal); except ShowMessage('浮点型数据转换错误!'); end; end;
为什么要保留2位?无非是显示的时候需要两位吧?如果是这样,显示的时候用format函数处理一下就行了。 如: var a:real; a:=3.1456; showmessage(format('%.2f',a));
Format 和 Round 都可以实现
Format 和 Round 都可以实现 一般用round
var a:real; a:=3.1456; showmessage(format('%.2f',a)); 同意: format('%.2f',a) 即可
参数说明:
InReal:取整浮点数
Len:小数位数
RoundOrTrunc:0:是四舍五入;1:截断,2: 有小数时向上取整
function RoundReal(InReal: real; Len: integer; RoundOrTrunc: integer=0): real;
var
I, numb: integer;
str: string;
begin
try
numb := 1;
for i := 0 to len - 1 do
numb := numb * 10;
if RoundOrTrunc = 0 then //四舍五入
result := Round(InReal * numb) / numb
else
if RoundOrTrunc = 1 then //截断
begin
Str := FloatToStr(InReal * numb);
if pos('.', Str) = 0 then
Result := InReal
else
begin
Str := Copy(str, 0, pos('.', Str) - 1);
result := StrToFloat(Str) / numb;
end;
end
else //2: 有小数时向上取整,返回一个整数。
result := Ceil(InReal);
except
ShowMessage('浮点型数据转换错误!');
end;
end;
如:
var
a:real; a:=3.1456;
showmessage(format('%.2f',a));
一般用round
a:real; a:=3.1456;
showmessage(format('%.2f',a));
同意:
format('%.2f',a)
即可