Delphi.cz

Český portál Delphi

TBCD v Delphi

Podle mne ne moc známá věc je implementace BCD v Delphi. BCD je způsob uložení čísel s fixní přesností. BCD je v Delphi reprezentován záznamem TBCD definovaným v jednotce Data.FmtBCD, případně FMTBcd (ve starších verzích, nejméně D2007).

V "novějších" verzích (XE2? +) je pro tento typ implementován class operator pro různé výchozí typy, takže podpora je celkem transparentní - jak je ukázáno v kódu.

uses
  SysUtils,
  Data.FMTBcd;

var
  a, b, c: TBcd;
  s: string;
begin
  try
    b := '10';     // implicit ze stringu
    a := 10000000;  // implicit z integer
    BcdDivide(b, a, c); // primo volani (pro starší verze)
    writeln(BcdToStr(c));

    c := b / a;   // pouzije class operator TBcd.Divide

    writeln(BcdToStr(c));
    s := string(c);      // explicit do stringu
    writeln(s);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Rozhraní dle Data.FmtBcd.TBcd:

  TBcd  = record
    Precision: Byte;                        { 1..64 }
    SignSpecialPlaces: Byte;                { Sign:1, Special:1, Places:6 }
    Fraction: packed array [0..31] of Byte; { BCD Nibbles, 00..99 per Byte, high Nibble 1st }
    class operator Implicit(const str: string): TBcd;
    class operator Implicit(const d: double): TBcd;
    class operator Implicit(const I: Integer): TBcd;
    class operator Explicit(const ABcd: TBcd): string;
    class operator Explicit(const ABcd: TBcd): Integer;
    class operator Add(const A, B: TBcd): TBcd;
    class operator Subtract(const A, B: TBcd): TBcd;
    class operator Multiply(const A, B: TBcd): TBcd;
    class operator Divide(const A, B: TBcd): TBcd;
    class operator Negative(const A: TBcd): TBcd;
    class operator Equal(const A, B: TBcd): Boolean;
    class operator NotEqual(const A, B: TBcd): Boolean;
    class operator GreaterThan(const A, B: TBcd): Boolean;
    class operator LessThan(const A, B: TBcd): Boolean;
    class operator GreaterThanOrEqual(const A, B: TBcd): Boolean;
    class operator LessThanOrEqual(const A, B: TBcd): Boolean;
  end;

Datum: 2017-01-30 23:03:00 Tagy: RTL

Praxe