How to Format a DBGrid Column to Display Two Decimal Places?

32,447

Solution 1

You can format the DBGrid columns by formatting the underlying fields. If not done, create static fields in your dataset and then set the DisplayFormat property of the field in question to 0.00 and you are done.

Solution 2

I use same method as Uwe answered, in code after opening the dataset just add this line of code to format certian column:

  TFloatField(MyDs.FieldByName('Cost')).DisplayFormat := '0.00';

Solution 3

You can format the field using the DrawDataCell event.

procedure TFormMain.DBGridCompareDrawDataCell(Sender: TObject;
  const Rect: TRect; Field: TField; State: TGridDrawState);
begin
  if Field.Name = 'FIELDNAME' then
    TFloatField(Field).DisplayFormat := '#,##0.00';
end;
Share:
32,447
Michael Riley - AKA Gunny
Author by

Michael Riley - AKA Gunny

Helping people get out of debt, one debt at a time. http://zilchworks.com Software Products: Zilch Standard - Debt Reduction Software Debt Manager Profesional Credit Card Math Favorite Languages: 1. Delphi / Object Pascal 2. SQL 3. VBScript / ASP

Updated on April 24, 2020

Comments

  • Michael Riley - AKA Gunny
    Michael Riley - AKA Gunny about 4 years

    I would like to format specific cells to force two decimal places. The data is coming from an ElevateDB stored procedure and hooked into a TDataSource.

    EDIT: SQL Programming Note:

    I wasn't sure if this was just an ElevateDB issue or not. Before knowing about the Fields Editor, I attempted to format the data at the SQL level by using a CAST (NumericField as varchar(10)) statement inside the stored procedure. By doing so, it did not expose the DisplayFormat property inside the fields editor for this particular field.

    When I removed the CAST() statement from the stored procedure, the DisplayFormat property showed up in the Fields Editor.

  • Michael Riley - AKA Gunny
    Michael Riley - AKA Gunny about 12 years
    How do you create "Static Fields"? How do you set the DisplayFormat?
  • Uwe Raabe
    Uwe Raabe about 12 years
    Use the fields editor to create static (also called persistent) fields. Each field has a property DisplayName.
  • Michael Riley - AKA Gunny
    Michael Riley - AKA Gunny about 12 years
    I "Right-Clicked" and found the "Fields Editor". However... there is no DisplayFormat. I am so frustrated with Delphi right now I could spit.
  • John Easley
    John Easley about 12 years
    Once inside the fields editor, right-click and select 'Add All Fields', then click on the field you want, and in the object inspector you should see the displayformat property, and set to ###.00
  • Michael Riley - AKA Gunny
    Michael Riley - AKA Gunny about 12 years
    Thanks for your patience... please read edit to OP.