{ Conversion between monetary amounts and integers. We do not use
  real numbers to avoid rounding inaccuracies and to not allow more
  than 2 digits after the decimal point (even if 0).

  @@ Currently hard-coded for two fractional digits (but not too
     hard to generalize).

  Copyright (C) 2002-2005 Frank Heckenbach <frank@pascal.gnu.de>

  This unit is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
  by the Free Software Foundation; either version 2, or (at your
  option) any later version.

  This unit is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this unit; see the file COPYING. If not, write to the
  Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  02111-1307, USA. }

{$if __GPC_RELEASE__ < 20030303}
{$error This program requires GPC release 20030303 or newer.}
{$endif}

unit MoneyUtils;

interface

uses GPC;

const
  MoneyComma: Char = ',';
  MoneyCommas: CharSet = ['.', ','];

function ValMoney (s: String; var Amount: LongInt): Boolean;
function FormatMoney (Amount: LongInt) = s: TString;

implementation

function ValMoney (s: String; var Amount: LongInt): Boolean;
var i, n, e, f: Integer;
begin
  ValMoney := False;
  TrimBoth (s);
  n := 0;
  for i := 1 to Length (s) do
    if s[i] in MoneyCommas then
      if n = 0 then
        n := i
      else
        Exit
    else if not (s[i] in ['0' .. '9']) then
      Exit;
  if n = 0 then
    f := 100
  else
    begin
      case Length (s) - n of
        0: f := 100;
        1: f := 10;
        2: f := 1;
        else Exit
      end;
      Delete (s, n, 1)
    end;
  Val (s, Amount, e);
  Amount := Amount * f;
  if (e <> 0) or (Amount < 0) or (Amount >= MaxInt) then Exit;
  ValMoney := True
end;

function FormatMoney (Amount: LongInt) = s: TString;
var i: Integer;
begin
  WriteStr (s, Abs (Amount) : 3);
  for i := 1 to Length (s) do
    if s[i] = ' ' then s[i] := '0';
  Insert (MoneyComma, s, Length (s) - 1);
  if Amount < 0 then Insert ('-', s, 1)
end;

end.
