[DUG] Need help in format function
John Bird
johnkbird at paradise.net.nz
Wed Mar 3 23:12:43 NZDT 2010
Tax calculations are tricky, as there are rules about either truncating to
whole dollars or down to whole cents. These are not maths functions, you
may have to make your own.
I have seen people do all sorts of tricks with formating floats as strings
and truncating, and converting back but to my mind the best is to calculate
in cents - which is what the rules are actually specifying. ie convert the
dollars to integer or int64 cents, do the calculation and convert the result
back to float. Otherwise you start getting oddities where Net + GST <>
Gross when the amounts are printed to dollars and cents.
Here is an example with GST calculations - guaranteeing that Net + GST =
Gross when printed as dollars and cents to 2 decimal places..:
//IRD guidelines are that GST calculated amount is rounded down to nearest
cent
procedure xcGSTCalc(aGSTRatePercent:double;var aNetVal:Double;var
aGSTVal:Double;var aInclVal:Double);
var
lGSTRate:int64; //gst rate as cents per 100 dollars (ie per 10000
cents)=GSTRate*100
lNetCents,lGSTCents,lInclCents:int64;
begin
lGSTRate:=trunc(aGSTRatePercent*100); //eg 1250
lNetCents:=round(aNetVal*100);
lGSTCents:=(lNetCents * lGSTRate) div 10000; //1250 div 10000 = .125
//note integer division
truncates fractions
lInclCents:=lNetCents+lGSTCents;
//return to float - this should guarantee nothing after first 2 decimal
places
aNetVal:=lNetCents/100;
aGSTVal:=lGSTCents/100;
aInclVal:=lInclCents/100;
end;
similar rules apply to with tax calculations - there is usually some
truncating to whole dollars or cents involved.
Incidentally this stuff fools the IRD too - for years the printed tax tables
have had some errors because they didn't follow their own truncating and
rounding rules for some calculations - and the printed tax tables did not
agree with their online tax calculator which was correct.
John
More information about the Delphi
mailing list