系统::货币和C 构建器

System::Currency and C++ Builder

本文关键字:构建 货币 系统      更新时间:2023-10-16

我正在使用Embarcadero C 构建器XE10来构建执行一些货币计算的应用程序。

尝试使用系统::货币数据类型时,我面临着几个问题。

Q1:为什么使用"%"操作员时,模量的计算失败?

System::Currency TaxValue = 1.665;
System::Currency Rest = 0;
// Correct result: Rest will be 0.005 when converted to double
Rest = TaxValue - ( TaxValue / 100 * 100 );
// Incorrect result: Rest is the same as TaxValue
Rest = TaxValue % 100;

编辑:我完全被调试器的输出所愚弄 系统::货币的价值以其整数代表乘以乘以 到10.000。

我真正期望看到的是:

Rest = (TaxValue * 10000) % 100;

==>现在休息是50,这正是我所期望的。

Q2:如何使用Curreny Data类型进行正确的银行家四舍五入?

示例:

1.664 => 1.66
1.665 => 1.67
1.666 => 1.67

herwig

Q1:为什么使用"%"操作员时,模量的计算失败?

System::Currency的精度为4个小数位。您的示例期望二位数精度。

System::Currency通过内部将输入值乘以10000,然后使用整数数学而不是浮点数数学来操纵值来维护其精度。

使用1.665初始化TaxValue时,其内部Val成员(即__int64(设置为(1.665 * 10000) = 16650。这是该构造函数的样子:

__fastcall Currency(double val) {Val = _roundToInt64(10000 * val);}

然后执行TaxValue % 100时,%运算符将像这样实现:

Currency __fastcall operator %(int rhs) const
{return Currency(static_cast<int>(Val % (10000 * (__int64)rhs))) / 10000;}

第一部分创建了一个temp Currency对象,该对象用int(16650 % (10000 * 100)) = 16650值初始化,该值由temp对象的构造函数乘以10000将CC_14乘以CC_14:

__fastcall Currency(int val) {Val = 10000*(__int64)val;}

第二部分将温度除以10000/运算符是这样实现的:

Currency& __fastcall operator /=(const Currency& rhs)
{Val *= 10000; Val /= rhs.Val; return *this;}
Currency __fastcall operator /(int rhs) const
{Currency tmp(*this); return tmp /= Currency(rhs);}

因此,生成最终的Currency对象,其Val已将其设置为(166500000 * 10000) / (10000 * 10000) = 16650

然后将最终Currency分配给Rest并将其转换为double时,该值由10000分配,从而产生1.665

__fastcall operator double() const {return ((double)Val) / 10000;}

Q2:如何使用Curreny Data类型进行正确的银行家四舍五入?

可以查看使用银行家的舍入的System::Round()功能。

如果您想对舍入更多控制权,请使用System::Math::RoundTo()功能或找到第三方圆形功能。

stackoverflow上还有其他几个问题,例如:

如何将Delphi货币类型像Excel一样圆形?

四舍五入货币

(System::Currency是Delphi的本机Currency类型的C 建造者的包装器(。