簡體   English   中英

是否有類似StrToCurr的函數可以處理數千個分隔符?

[英]Is there a StrToCurr like function that can deal with thousand separators?

在這個問題上也有類似的情況。

procedure TForm2.FormCreate(Sender: TObject);
var
  S: string;
  C: Currency;
  FormatSettings: TFormatSettings;
begin
  S := '1.000.000,00';
  FormatSettings := TFormatSettings.Create;
  FormatSettings.ThousandSeparator := '.';
  FormatSettings.DecimalSeparator := ',';
  // raises an Exception which is "as designed" as per the documentation
  C := StrToCurr(S, FormatSettings);
  ShowMessage(FormatCurr(',0.00', C));
end;

引用大衛:

因此,將包含數千個分隔符的字符串傳遞給此函數是錯誤的。

那么,Delphi是否具有任何內置函數可以解析包含千位分隔符的貨幣字符串?

該設計(缺陷)的解決方案很簡單:定義自己的功能。

unit MyFixForSysUtils;

interface

function StrToCurr(const Str: string): Currency; overload;
function StrToCurr(Str: string; const FormatSettings : TFormatSettings): Currency; overload;  

implementation

uses SysUtils;

function StrToCurr(Str: string; const FormatSettings : TFormatSettings): Currency;
begin
  Str:= StringReplace(Str, FormatSettings.ThousandSeparator, '', [rfReplaceAll]);
  Result:= SysUtils.StrToCurr(Str, FormatSettings);
end;

 function StrToCurr(const Str: string): Currency;
 begin
   Result:= StrToCurr(Str, FormatSettings);
 end;

如果您確定自己的版本在范圍上比sysutils更近,那么您無需更改代碼:

uses
  SysUtils,
  MyFixForSysUtils,  <-- contains the above function
  .... other units.

現在,Delphi將選擇固定功能而不是損壞的功能。

有關此概念的更多信息,請參見: Delphi插入器

您可以使用VarCyFromStr從“varutils.pas”在默認情況下指向COM幫手VarCyFromStr在“activex.pas”(你可以直接使用)從“OLEAUT32”進口。

如果您知道該字符串已使用系統默認語言環境進行了本地化,則可以使用:

var
  S: string;
  C: Currency;
begin
  S := '1.000.000,00';
  if varutils.VarCyFromStr(S, 0, LOCALE_NOUSEROVERRIDE, C) = VAR_OK then
    ShowMessage(FormatCurr(',0.00', C))
  else

或通過GetThreadLocale獲取LCID以使用當前線程的設置。

如果使用默認的用戶區域設置對字符串進行了本地化,則可以使RTL為您調用該字符串,並使用此函數進行變體轉換。

var
  V: Variant;
  C: Currency;
begin
  V := '1.000.000,00';
  C := V;
  ShowMessage(FormatCurr(',0.00', C));

否則,您必須知道字符串在哪種語言環境中表示貨幣。 例:

var
  S: string;
  C: Currency;
begin
  S := '1,000,000.00';
  if varutils.VarCyFromStr(S, MAKELCID(LANG_ENGLISH, SORT_DEFAULT), 0, C) = VAR_OK then
    ShowMessage(FormatCurr(',0.00', C))
  else
    // handle error

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM