Frequently Asked Component Specific Questions

Options

Display all FAQ items

Search FAQ items:


Displaying items 1 to 1 of 1, page 1 of 1

<< previous next >>

TAdvStringGrid
Dealing with floating point number precision in TAdvStringGrid

When wanting to keep floating point numbers with high precision in the grid but display with less precision, the OnGetFloatFormat event can be used. In this code snippet, the grid cell value is set with a floating point number with 8 digits but is displayed with only 3 digits precision. Internally, we can keep calculating with values with 8 digits.

Sample:

// Set float value with full precision
begin
  advstringgrid1.FloatFormat := ''%g'';
  advstringgrid1.Floats[1,1] := 1.23456789;
  advstringgrid1.Floats[1,2] := 9.87654321;
end;

// ensure floating point number is only displayed with 3 digits
procedure TForm4.AdvStringGrid1GetFloatFormat(Sender: TObject; ACol,
  ARow: Integer; var IsFloat: Boolean; var FloatFormat: string);
begin
  FloatFormat := ''%.3f'';
end;

// do calculation at full precision
begin
  advstringgrid1.Floats[1,3] := advstringgrid1.Floats[1,1] + advstringgrid1.Floats[1,2];
end;
This displays the rounded numbers in the grid:
1.235
9.877
but the displayed result is
11.111
as the sum calculated is based on full precision.