Title: Currency rounding
Question: How to round the datatype Currency using only integer arithmetic
Answer:
the following function rounds a Currency value to the given number of digits.
The datatype Currency is a fixed point format and consumes 8 bytes in memory.
Instead of converting currency to Extended (and back) this function use only (64bit-) integer arithmetics.
examples:
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 has only 4 digits after the decimalseparator
if (nk=4) or (Value=0) then
begin
Result := Value;
Exit;
end;
if nk then
raise EInvalidArgument.CreateFmt('RoundCurrency(,%d): invalid arg', [nk]);
// cast Currency to Int64
x := PInt64(@Value)^;
y := faktors[nk];
// rounding
if x 0 then
x := ((x+(y div 2)) div y)*y
else
x := ((x-(y div 2)) div y)*y;
// cast Int64 to Currency
Result := PCurrency(@x)^;
end;
Please read this article, too:
Rounding numbers in different ways