Decimals??
Hi
I have created a calculated field which determines the average of two sets of figures. Here is my code in the OnCalculatedFields event :
Try
Dataset.FieldByName('calcAverage').AsSingle:=
Dataset.FieldByName('TotalPoints').AsInteger div Dataset.FieldByName('MatchesPlayed').AsInteger;
Except
On E : EDivByZero do
Dataset.FieldByName('calcAverage').AsSingle:= 0; //Usually as member who enrolled hasn't had a game yet!
End;
The problem is that none of the results from the above give any answers with decimal points. This is wrong as many of the calculations should be giving decimal answers. So how do you get the exact answers from a calculated field?
Accepted Answer
What did you define the Calculated Field CalcAverage as when you defined it?
Var:
fAve: Single;
nTotPts: Integer;
nMatPla: Integer;
begin
nTotPts := StrToIntDef(Dataset.FieldByName('TotalPoints').AsString, 0);
nMatPla := StrToIntDef(Dataset.FieldByName('MatchesPlayed').AsString, 0);
if (nTotPts >0) and (nMatPla > 0) then
fAve := nTotPts / nMatPla
else fAve := 0.00;
Dataset.FieldByName('CalcAverage').AsSingle := fAve;
end;
-
Accepted Answer
0Marko,
Many thanks, this has finally cracked it and gives the results I was expecting (that is with decimal places).
I defined the calculated field as Float. I see a simpler way of avoiding the divide by zero issue. Thanks again for the code.
Barry
-
Accepted Answer
0Hi
That's not true, 5 divided by 3 is not an integer result.
The result field needs to be float, I can see that, but when I divide an integer into an integer I want the exact result (well to a couple of decimal places for this app).
Unless there is some bug in the functionality, I can't for the life of me see what's wrong with my code :-)
-
Accepted Answer
0Hi Bazzer
Dataset.FieldByName('TotalPoints').AsInteger
Needs to be
Dataset.FieldByName('TotalPoints').AsFloat
Otherwise you are doing a division of two integers - which gives an integer result.
Regards, Roger
-
Accepted Answer
0Hi
Thanks for the suggestion. However, that doesn't seem to work either. My code now looks like this:
Try
Dataset.FieldByName('calcAverage').AsFloat:=
Dataset.FieldByName('TotalPoints').AsInteger /
Dataset.FieldByName('MatchesPlayed').AsInteger;
Except
On E : EDivByZero do
Dataset.FieldByName('calcAverage').AsFloat:= 0; //Usually as member who enrolled hasn't had a game yet!
End;I changed the div operator to /, as the div (I now know) only returns integers)
This compiles OK but when it runs I get an application error 'invalid floating point operation'. TotalPoints is a calculated field in MSSQL which simply adds up several other integer fields (like MatchesPlayed).