Arredondamento de Currency
A seguinte função faz o arredondamento de um valor Currency para um determinado número de dígitos. O datatype Currency é um formato de ponto fixo e consome 8 bytes de memória.
Em vez de converter Currency para Extended (e vice-versa) essa função utiliza só aritmética de inteiros (64bit -).
Exemplos:
RoundCurrency(1.2520, 1) => 1.3
RoundCurrency(-99.5, 0) => -100
RoundCurrency(-99.4999, 0) => -99
function RoundCurrency(const Value: Currency; const nk: Integer): Currency;
const
faktors : array[-3..3] of Integer = (10000000, 1000000, 100000, 10000, 1000, 100, 10);
var
x : Int64;
y : Int64;
begin
{ Currency tem somente 4 digitos após a vírgula decimal }
if (nk>=4) or (Value=0) then
begin
Result := Value;
Exit;
end;
if nk < Low(faktors) then
raise EInvalidArgument.CreateFmt('RoundCurrency(,%d): invalid arg', [nk]);
{ cast de Currency para Int64 }
x := PInt64(@Value)^;
y := faktors[nk];
{ arredondando }
if x > 0 then
x := ((x+(y div 2)) div y)*y
else
x := ((x-(y div 2)) div y)*y;
{ cast de Int64 para Currency }
Result := PCurrency(@x)^;
end;