小数位数的保留代码
最近写了两个小工具,要将小数部分四舍五入至一位小数和整数,可函数中round()是所谓的银行家进位法,实在用不了。无奈找度娘询问了一阵,结果不尽人情呀,最后找到一个保留两位小数的代码,通过修改后令人满意。现分享大家留着备用:
============================
保留1位小数
===========================
function BL1(s: real): real;
var
r1, r2: real;
s1, s2: string;
begin
r1 := int(s);
r2 := frac(s);
s1 := copy(floattostr(r1), 1, length(floattostr(r1)));
if length(floattostr(r2)) >= 4 then
begin
if strtoint(copy((floattostr(r2)), 4, 1)) >= 5 then //小数第三位开始复制一位0.00
if strtoint(copy((floattostr(r2)), 3, 1)) = 9 then
============================
保留1位小数
===========================
function BL1(s: real): real;
var
r1, r2: real;
s1, s2: string;
begin
r1 := int(s);
r2 := frac(s);
s1 := copy(floattostr(r1), 1, length(floattostr(r1)));
if length(floattostr(r2)) >= 4 then
begin
if strtoint(copy((floattostr(r2)), 4, 1)) >= 5 then //小数第三位开始复制一位0.00
if strtoint(copy((floattostr(r2)), 3, 1)) = 9 then
begin
s1 := inttostr(strtoint(s1) + 1);
s2 := '';
end
else
S2 := inttostr(strtoint(copy((floattostr(r2)), 3, 1)) + 1)
else if copy((floattostr(r2)), 3, 1) = '0' then
s2:=''
else s2 := copy(floattostr(r2), 3, 1);
end
else s2 := copy(floattostr(r2), 3, 1);
result := strtofloat(s1 + '.' + s2);
end;
s1 := inttostr(strtoint(s1) + 1);
s2 := '';
end
else
S2 := inttostr(strtoint(copy((floattostr(r2)), 3, 1)) + 1)
else if copy((floattostr(r2)), 3, 1) = '0' then
s2:=''
else s2 := copy(floattostr(r2), 3, 1);
end
else s2 := copy(floattostr(r2), 3, 1);
result := strtofloat(s1 + '.' + s2);
end;
====================
调用
=====================
label3.Caption :=floattostr(BL(strtofloat(edit1.text)));
调用
=====================
label3.Caption :=floattostr(BL(strtofloat(edit1.text)));
================================
四舍五入到整数
================================
function BL0(s: real): real;
var
r1, r2: real;
s1, s2: string;
begin
r1 := int(s); //取整数部分
r2 := frac(s); //取小数部分
s1 := copy(floattostr(r1), 1, length(floattostr(r1))); //复制R1,复制位数为R1长度
if length(floattostr(r2)) >= 3 then //如果小数部分长度>=3
四舍五入到整数
================================
function BL0(s: real): real;
var
r1, r2: real;
s1, s2: string;
begin
r1 := int(s); //取整数部分
r2 := frac(s); //取小数部分
s1 := copy(floattostr(r1), 1, length(floattostr(r1))); //复制R1,复制位数为R1长度
if length(floattostr(r2)) >= 3 then //如果小数部分长度>=3
if strtoint(copy((floattostr(r2)), 3, 1)) >= 5 then //从小数部分第三位开始复制一位数
s1 := inttostr(strtoint(s1) + 1); //如果第一位小数大于5就向整数个位进1
result := strtofloat(s1);
end;
result := strtofloat(s1);
end;