如何将浮点数或货币转换为本地化字符串?

Ian*_*oyd 15 delphi string localization internationalization delphi-5

在Delphi 1中,使用FloatToStrFCurrToStrF将自动使用该DecimalSeparator字符表示小数点.不幸的DecimalSeparator 是在SysUtils中声明为Char1,2:

var 
  DecimalSeparator: Char;
Run Code Online (Sandbox Code Playgroud)

虽然LOCALE_SDECIMAL被允许最多为三个字符:

用于小数分隔符的字符,例如"." 在"3.14"或","在"3,14"中.此字符串允许的最大字符数为4,包括终止空字符.

这导致Delphi无法正确读取小数分隔符; 回退假设一个默认的小数分隔符" .":

DecimalSeparator := GetLocaleChar(DefaultLCID, LOCALE_SDECIMAL, '.');
Run Code Online (Sandbox Code Playgroud)

在我的计算机上,这是一个非常字符,这会导致浮点数和货币值错误地本地化为U + 002E(句号)小数点.

愿意直接调用Windows API函数,其目的是为了浮点或货币值转换为一个本地化的字符串:

除了这些函数之外,还需要一串图片代码,其中唯一允许的字符是:

  • 字符"0"到"9"(U+0030.. U+0039)
  • 一个小数点(.),如果数字是浮点值(U+002E)
  • 如果数字为负值,则在第一个字符位置显示减号(U+002D)

这将是一个很好的方式1至浮点或货币价值转换为遵守这些规则的字符串?例如

  • 1234567.893332
  • -1234567

鉴于本地用户的语言环境(即我的电脑):


一个可怕的,可怕的,黑客,我可以使用:

function FloatToLocaleIndependantString(const v: Extended): string;
var
   oldDecimalSeparator: Char;
begin
   oldDecimalSeparator := SysUtils.DecimalSeparator;
   SysUtils.DecimalSeparator := '.'; //Windows formatting functions assume single decimal point
   try
      Result := FloatToStrF(Value, ffFixed, 
            18, //Precision: "should be 18 or less for values of type Extended"
            9 //Scale 0..18.   Sure...9 digits before decimal mark, 9 digits after. Why not
      );
   finally
      SysUtils.DecimalSeparator := oldDecimalSeparator;
   end;
end;
Run Code Online (Sandbox Code Playgroud)

有关VCL使用的功能链的其他信息:

注意

1在我的Delphi
2版本和当前版本的Delphi中

Ian*_*oyd 3

Delphi 确实提供了一个名为 的过程FloatToDecimal,可以将浮点(例如Extended)和Currency值转换为有用的结构以进行进一步格式化。例如:

FloatToDecimal(..., 1234567890.1234, ...);
Run Code Online (Sandbox Code Playgroud)

给你:

TFloatRec
   Digits: array[0..20] of Char = "12345678901234"
   Exponent: SmallInt =           10
   IsNegative: Boolean =          True
Run Code Online (Sandbox Code Playgroud)

其中Exponent给出小数点左边的位数。

有一些特殊情况需要处理:

  • 指数为零

       Digits: array[0..20] of Char = "12345678901234"
       Exponent: SmallInt =           0
       IsNegative: Boolean =          True
    
    Run Code Online (Sandbox Code Playgroud)

    表示小数点左边没有数字,例如.12345678901234

  • 指数为负数

       Digits: array[0..20] of Char = "12345678901234"
       Exponent: SmallInt =           -3
       IsNegative: Boolean =          True
    
    Run Code Online (Sandbox Code Playgroud)

    意味着您必须在小数点和第一位数字之间放置零,例如.00012345678901234

  • 指数是-32768NaN,不是数字)

       Digits: array[0..20] of Char = ""
       Exponent: SmallInt =           -32768
       IsNegative: Boolean =          False
    
    Run Code Online (Sandbox Code Playgroud)

    表示该值不是数字,例如NAN

  • 指数为32767INF-INF

       Digits: array[0..20] of Char = ""
       Exponent: SmallInt =           32767
       IsNegative: Boolean =          False
    
    Run Code Online (Sandbox Code Playgroud)

    表示该值是正无穷大或负无穷大(取决于该IsNegative值),例如-INF


我们可以以此FloatToDecimal为起点来创建与区域设置无关的“图片代码”字符串。

然后可以将该字符串传递到适当的 WindowsGetNumberFormatGetCurrencyFormat函数以执行实际的正确本地化。

我自己编写了CurrToDecimalString它将FloatToDecimalString数字转换为所需的独立于语言环境的格式:

class function TGlobalization.CurrToDecimalString(const Value: Currency): string;
var
    digits: string;
    s: string;
    floatRec: TFloatRec;
begin
    FloatToDecimal({var}floatRec, Value, fvCurrency, 0{ignored for currency types}, 9999);

    //convert the array of char into an easy to access string
    digits := PChar(Addr(floatRec.Digits[0]));

    if floatRec.Exponent > 0 then
    begin
        //Check for positive or negative infinity (exponent = 32767)
        if floatRec.Exponent = 32767 then //David Heffernan says that currency can never be infinity. Even though i can't test it, i can at least try to handle it
        begin
            if floatRec.Negative = False then
                Result := 'INF'
            else
                Result := '-INF';
            Exit;
        end;

        {
            digits:    1234567 89
              exponent--------^ 7=7 digits on left of decimal mark
        }
        s := Copy(digits, 1, floatRec.Exponent);

        {
            for the value 10000:
                digits:   "1"
                exponent: 5
            Add enough zero's to digits to pad it out to exponent digits
        }
        if Length(s) < floatRec.Exponent then
            s := s+StringOfChar('0', floatRec.Exponent-Length(s));

        if Length(digits) > floatRec.Exponent then
            s := s+'.'+Copy(digits, floatRec.Exponent+1, 20);
    end
    else if floatRec.Exponent < 0 then
    begin
        //check for NaN (Exponent = -32768)
        if floatRec.Exponent = -32768 then  //David Heffernan says that currency can never be NotANumber. Even though i can't test it, i can at least try to handle it
        begin
            Result := 'NAN';
            Exit;
        end;

        {
            digits:   .000123456789
                         ^---------exponent
        }

        //Add zero, or more, "0"'s to the left
        s := '0.'+StringOfChar('0', -floatRec.Exponent)+digits;
    end
    else
    begin
        {
            Exponent is zero.

            digits:     .123456789
                            ^
        }
        if length(digits) > 0 then
            s := '0.'+digits
        else
            s := '0';
    end;

    if floatRec.Negative then
        s := '-'+s;

    Result := s;
end;
Run Code Online (Sandbox Code Playgroud)

NAN除了、INF和的边缘情况之外-INF,我现在可以将这些字符串传递给 Windows:

class function TGlobalization.GetCurrencyFormat(const DecimalString: WideString; const Locale: LCID): WideString;
var
    cch: Integer;
    ValueStr: WideString;
begin
    Locale
        LOCALE_INVARIANT
        LOCALE_USER_DEFAULT     <--- use this one (windows.pas)
        LOCALE_SYSTEM_DEFAULT
        LOCALE_CUSTOM_DEFAULT       (Vista and later)
        LOCALE_CUSTOM_UI_DEFAULT    (Vista and later)
        LOCALE_CUSTOM_UNSPECIFIED   (Vista and later)
}

    cch := Windows.GetCurrencyFormatW(Locale, 0, PWideChar(DecimalString), nil, nil, 0);
    if cch = 0 then
        RaiseLastWin32Error;

    SetLength(ValueStr, cch);
    cch := Windows.GetCurrencyFormatW(Locale, 0, PWideChar(DecimalString), nil, PWideChar(ValueStr), Length(ValueStr));
    if (cch = 0) then
        RaiseLastWin32Error;

    SetLength(ValueStr, cch-1); //they include the null terminator  /facepalm
    Result := ValueStr;
end;
Run Code Online (Sandbox Code Playgroud)

FloatToDecimalStringGetNumberFormat实现留给读者作为练习(因为我实际上还没有编写浮点型,只是货币 - 我不知道如何处理指数表示法)。

还有鲍勃的叔叔;Delphi 下正确本地化的浮动和货币。

我已经完成了正确本地化整数、日期、时间和日期时间的工作。

注意:任何代码都会发布到公共领域。无需归属。