加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 10:09:28 所属栏目:大数据 来源:网络整理
导读:在Delphi1中,使用FloatToStrF或CurrToStrF会自动使用DecimalSeparator字符来表示小数点.不幸的是DecimalSeparator is declared in SysUtils as Char 1,2 : var DecimalSeparator: Char; 而 LOCALE_SDECIMAL 允许最多三个字符: Character(s) used for the d
在Delphi1中,使用FloatToStrF或CurrToStrF会自动使用DecimalSeparator字符来表示小数点.不幸的是DecimalSeparator is declared in SysUtils as Char1,2
var 
  DecimalSeparator: Char;

LOCALE_SDECIMAL允许最多三个字符:

Character(s) used for the decimal separator,for example,“.” in “3.14” or “,” in “3,14”. The maximum number of characters allowed for this string is four,including a terminating null character.

这导致Delphi无法正确读取小数分隔符;退回以假定“.”的默认小数分隔符:

DecimalSeparator := GetLocaleChar(DefaultLCID,LOCALE_SDECIMAL,'.');

在我的电脑上,which is quite a character,这样会导致浮点数和货币值错误地以U+002E(全停)小数点进行本地化.

我愿意直接调用Windows API函数,这些函数旨在将浮点值或货币值转换为本地化的字符串:

> GetNumberFormat
> GetCurrencyFormat

除了这些功能需要一串图片代码,其中唯一允许的字符是:

>字符“0”到“9”(U 0030..U 0039)
>一个小数点(.)如果数字是一个浮点值(U 002E)
>如果数字为负值(U 002D),则第一个字符位置中的减号

将浮点值或货币值转换为符合这些规则的字符串将是一个好办法1?例如

> 1234567.893332
> -1234567

鉴于本地用户的区域设置(即我的电脑):

>可能不会使用 – 来表示否定(例如 – )
> might not use a . to indicate a decimal point(例如,)
> might not use the latin alphabet 0123456789 to represent digits(例如[删除阿拉伯数字,崩溃SO JavaScript解析器])

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

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;

VCL使用的功能链附加信息:

> FloatToStrFCurrToStrF电话:

> FloatToText电话:

> FloatToDecimal

注意

> DecimalSeparator:Char,单个character global is deprecated,并替换为另一个单字符小数分隔符

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

解决方法

好的,这可能不是你想要的,但它适用于D2007及以上.
线程安全和所有.
uses Windows,SysUtils;

var
  myGlobalFormatSettings : TFormatSettings;

// Initialize special format settings record
GetLocaleFormatSettings( 0,myGlobalFormatSettings);
myGlobalFormatSettings.DecimalSeparator := '.';


function FloatToLocaleIndependantString(const value: Extended): string;
begin
  Result := FloatToStrF(Value,//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
        myGlobalFormatSettings
  );
end;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读