Reputation: 3699
I have such a table in SQLite :
CREATE TABLE [TABLE1] (
[T_ID] INTEGER PRIMARY KEY ON CONFLICT IGNORE AUTOINCREMENT,
[DATE] DATE UNIQUE ON CONFLICT IGNORE,
[FIELD1] INTEGER,
[FIELD2] INTEGER,
[FIELD3] INTEGER,
[FIELD4] REAL);
I added a 2 new calculated fields to the TABLE1 called SUM1 (integer) and SUM2 (float).
procedure TForm3.UniTable1CalcFields(DataSet: TDataSet);
begin
UNITable1.Fields.FieldByName('SUM1').asInteger := (UNITable1.Fields.FieldByName('FIELD1').AsInteger) + (UNITable1.Fields.FieldByName('FIELD2').AsInteger) + (UNITable1.Fields.FieldByName('FIELD3').AsInteger);
UNITable1.Fields.FieldByName('SUM2').asFloat := (UNITable1.Fields.FieldByName('SUM1').AsInteger) / (UNITable1.Fields.FieldByName('FIELD4').AsInteger) ;
end;
This kind of works but I am having trouble vwith SUM2 displaying a 15 digit number.
I would like to display a number with only two decimals like 5,81. I could do it in the cxGrid by setting the properties of the field to CalcEdit and set Precision to 3. But I am wondering can this be done in code.
Is there a way I can accomplish this ?
Upvotes: 0
Views: 222
Reputation: 109
Another option is to use the FormatFloat('0.00',myvariable)
function.
'0.00' defines the format (2 decimal places), and myvariable is an aptly named variable.
The only drawbacks are that it requires an extra few lines of code to declare and assign a value to the variable, and if you wish to use this value for further calculations, the accuracy will be lower than the original floating point number you had.
procedure TForm3.UniTable1CalcFields(DataSet: TDataSet);
var
var1: real;
begin
//Assign the floating point value to the variable
var1 := (UNITable1.Fields.FieldByName('SUM1').AsInteger) / (UNITable1.Fields.FieldByName('FIELD4').AsInteger);
UNITable1.Fields.FieldByName('SUM1').asInteger := UNITable1.Fields.FieldByName('FIELD1').AsInteger) + (UNITable1.Fields.FieldByName('FIELD2').AsInteger) + (UNITable1.Fields.FieldByName('FIELD3').AsInteger);
UNITable1.Fields.FieldByName('SUM2').AsFloat := FormatFloat('0.00',var1);
end;
i haven't had a chance to test this, but the basic idea would be something along these lines.
Upvotes: 0
Reputation: 379
Well 314 / 54 is 5.814814814814... . If you are using persistent fields you can set the DisplayFormat to ',0.00;; '
or in code:
TNumericField(UNITable1.Fields.FieldByName('SUM2')).DisplayFormat := ',0.00;; ';
Upvotes: 4