德尔福兑换货币[关闭]

问题描述 投票:-5回答:1

嗨,我想将某种货币换成另一种货币,比如从美元到欧元,还有其他任何货币,我不知道怎么做,有人可以帮助我吗?

delphi currency
1个回答
2
投票

您可以轻松使用以下方法作为指南:

function EuroToDollar(amount: integer): double;
begin
  Result := amount * 1.17;
end;

我从谷歌那里获得了1.17,但你可以在任何地方轻松找到转换率。


这种方法很好但不灵活,因为如果考虑到有很多货币,你应该创建很多功能。我创建了这个简单的VCL应用程序:

type
  TCurrency = (cEuro, cDollar, cWhatever);
  TConversion = reference to function(target: TCurrency; amount: double): double;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    CurrencyList: TDictionary<TCurrency, TConversion>;
  public
    function Convert(fromCurr: TCurrency; toCurr: TCurrency; amount: double): double;
  end;

我使用字典来存储您必须使用的货币和转换方法。

//example
procedure TForm1.Button1Click(Sender: TObject);
var
  euro, dollar: double;
begin
  //euro-dollar
  euro := Convert(cEuro, cDollar, 2);
  ShowMessage(euro.ToString);

  //dollar-euro
  dollar := Convert(cDollar, cEuro, 5);
  ShowMessage(dollar.ToString);
end;

function TForm1.Convert(fromCurr, toCurr: TCurrency; amount: double): double;
begin
  Result := CurrencyList[fromCurr](toCurr, amount);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  CurrencyList := TDictionary<TCurrency, TConversion>.Create();

  CurrencyList.Add(TCurrency.cEuro, function(target: TCurrency; amount: double): double
                                    begin
                                      case target of
                                        cDollar:
                                          begin
                                            Result := amount * 1.17;
                                          end;
                                      end;
                                    end);

  CurrencyList.Add(TCurrency.cDollar, function(target: TCurrency; amount: double): double
                                      begin
                                        case target of
                                          cEuro:
                                            begin
                                              Result := amount * 0.86;
                                            end;
                                        end;
                                      end);
end;

通过这种方式,您可以定义货币,然后只需在case中添加新值即可添加转换。这是我认为你可以做的一个框架,但可能会有更多(比如从网站获取转换常量),但这超出了答案的范围。

© www.soinside.com 2019 - 2024. All rights reserved.