使 VarToDoubleAsString 使用 Delphi 设置(而不是操作系统设置)
当将包含字符串值的 Variant 分配给浮点变量时,Delphi 调用 VarToDoubleAsString 进行转换,该转换又使用操作系统设置的小数点和千位分隔符(通过 VarR8FromStr)。如果必须更改 SysUtils.DecimalSeparator 和 SysUtils.ThousandSeparator ,就会出现问题。例如,运行以下程序:
program VarStrToFloat;
{$APPTYPE CONSOLE}
uses
SysUtils,
Math;
function FormatFloatUsingDelphiSettings(Value: Extended): string;
begin
Result := FormatFloat('#,##0.00', Value);
end;
procedure Test(const AMsg: string);
var
r1, r2: Extended;
s1, s2: string;
v: Variant;
begin
r1 := 5432.1;
s1 := FormatFloatUsingDelphiSettings(r1);
v := s1; // <== conversion uses OS settings
r2 := v;
s2 := FormatFloatUsingDelphiSettings(r2);
Write(AMsg: 8, s1: 10, s2: 10, ' ');
if SameValue(r1, r2) then
Writeln('OK')
else
Writeln('FAIL');
end;
procedure SwapEm;
var
tmp: Char;
begin
tmp := DecimalSeparator;
DecimalSeparator := ThousandSeparator;
ThousandSeparator := tmp;
end;
begin
Test('Default');
SwapEm;
Test('Changed');
Readln;
end.
第一个测试工作正常,第二个测试失败。
有没有办法使 Variant 转换使用 SysUtils.DecimalSeparator 和 SysUtils.ThousandSeparator ?
When one assigns a Variant containing a string value to a floating point variable Delphi calls VarToDoubleAsString to do the conversion, which in turn uses the OS settings for decimal and thousand separator (via VarR8FromStr). This is problematic if one has to change SysUtils.DecimalSeparator
and SysUtils.ThousandSeparator
. For example run the following program:
program VarStrToFloat;
{$APPTYPE CONSOLE}
uses
SysUtils,
Math;
function FormatFloatUsingDelphiSettings(Value: Extended): string;
begin
Result := FormatFloat('#,##0.00', Value);
end;
procedure Test(const AMsg: string);
var
r1, r2: Extended;
s1, s2: string;
v: Variant;
begin
r1 := 5432.1;
s1 := FormatFloatUsingDelphiSettings(r1);
v := s1; // <== conversion uses OS settings
r2 := v;
s2 := FormatFloatUsingDelphiSettings(r2);
Write(AMsg: 8, s1: 10, s2: 10, ' ');
if SameValue(r1, r2) then
Writeln('OK')
else
Writeln('FAIL');
end;
procedure SwapEm;
var
tmp: Char;
begin
tmp := DecimalSeparator;
DecimalSeparator := ThousandSeparator;
ThousandSeparator := tmp;
end;
begin
Test('Default');
SwapEm;
Test('Changed');
Readln;
end.
The first test works fine, the second one fails.
Is there a way to make the Variant conversion use SysUtils.DecimalSeparator
and SysUtils.ThousandSeparator
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以根据自己的喜好替换
varutils.pas
中的VarR8FromStr
函数,VarToDoubleAsString
将使用它:You can replace the
VarR8FromStr
function invarutils.pas
to your liking, andVarToDoubleAsString
will use it instead: