gpt4 book ai didi

Delphi - RoundTo - 总是向下

转载 作者:行者123 更新时间:2023-12-02 01:33:53 27 4
gpt4 key购买 nike

我需要将 float 四舍五入到小数点后两位,但总是向下舍入。现在我使用 RoundTo(number, -2),但它在数学上正确地进行舍入,这对于我的情况来说是不期望的行为。把原因,为什么我需要这样做,放在一边......

我最终用这个实现了它:

var a,b: currency;
floatStr: string;
format: TFormatSettings;
localeDec: char;
begin


format:= TFormatSettings.Create;
localeDec:= format.DecimalSeparator;
format.DecimalSeparator:= ',';
System.SysUtils.FormatSettings:= format;

a:= 2/30;
floatStr:= floatToStr(a);
b:= strToCurr(
copy(floatStr, 1, ansiPos(',', floatStr) + 2)
);
showMessage(currToStr(b));

format.DecimalSeparator := localeDec;
System.SysUtils.FormatSettings:= format;

end;

但是,这个解决方案感觉不太正确。有没有一种“数学上干净”的方法来做到这一点,而不会弄乱字符串和重置小数分隔符等?我查了很多,但没有找到。

最佳答案

您可以执行以下操作:

  1. 将该值乘以 100。
  2. 截断为整数,接近零。
  3. 将该值除以 100。

像这样:

function RoundCurrTo2dpTruncate(const Value: Currency): Currency;
begin
Result := Trunc(Value*100) / 100;
end;

我假设向下舍入意味着朝零方向舍入。因此 0.678 向下舍入为 0.67,-0.678 向下舍入为 -0.67。但是,如果您想向 -∞ 舍入,则应将 Trunc 替换为 Floor

function RoundCurrTo2dpDown(const Value: Currency): Currency;
begin
Result := Floor(Value*100) / 100;
end;

解决该问题的另一种方法是认识到 Currency 值只是一个隐式移位 10000 的 64 位整数。因此,与代码不同,整个操作可以使用整数运算来执行上面使用了浮点运算。

来自documentation :

Currency is a fixed-point data type that minimizes rounding errors in monetary calculations. It is stored as a scaled 64-bit integer with the 4 least significant digits implicitly representing decimal places. When mixed with other real types in assignments and expressions, Currency values are automatically divided or multiplied by 10000.

例如,您可以像这样实现 RoundCurrTo2dpTruncate:

function RoundCurrTo2dpTruncate(const Value: Currency): Currency;
begin
PInt64(@Result)^ := (PInt64(@Value)^ div 100)*100;
end;

请注意,这里的算术运算已移位 10000。因此,乘以 100 变为除以 100。依此类推。

关于Delphi - RoundTo - 总是向下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675058/

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