gpt4 book ai didi

delphi - 高效,准确地将货币类型转换为整数

转载 作者:行者123 更新时间:2023-12-03 07:26:19 25 4
gpt4 key购买 nike

如果可能的话,我想避免在类似于以下代码的情况下将Currency转换为Extended(并可能会降低精度):

function CurrencyToNumeric(aCurrency: Currency; aScale: Integer): Int64;
const
scales: array [-{18}5..-1] of int64 = (100000, 10000, 1000, 100, 10);
var
aCurrencyAsInt64: Int64 absolute aCurrency;
begin
if aScale = -4 then
Result := aCurrencyAsInt64
else
Result := Round(aCurrency * scales[aScale]); // currency -> extended -> integer
end;

那可能吗?

最佳答案

我相信您正在寻找这样的功能:

function CurrencyToNumeric(aCurrency: Currency; aScale: Integer): int64;
var
aCurrencyAsInt64: int64 absolute aCurrency;
i, factor, rem: Integer;
begin
if aScale <= -4 then begin
factor := 1;
for i := -4 downto aScale+1 do begin
factor := factor * 10;
end;
Result := aCurrencyAsInt64 * factor;
end else begin
factor := 1;
for i := -4 to aScale-1 do begin
factor := factor * 10;
end;
Result := aCurrencyAsInt64 div factor;
rem := aCurrencyAsInt64 mod factor;
if rem>=factor div 2 then begin
inc(Result);
end;
end;
end;

这部分代码
if rem>=factor div 2 then begin
inc(Result);
end;

实现舍入策略。您可能希望做出其他选择。修改此代码以执行此操作,应该很明显地做到这一点。

但是,我也不相信问题中的版本已损坏。在失败的地方有示例输入吗?另一方面,避免将定点十进制类型转换为二进制浮点确实是明智的。现在,如果只有Embarcadero实现了这种织补类型而不使用浮点运算。

关于delphi - 高效,准确地将货币类型转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42859038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com