系统::货币和C 构建器
System::Currency and C++ Builder
我正在使用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 建造者的包装器(。
- C++为构建时间获取QDateTime的可靠方法
- 无法在 CLion 中构建 C++ 项目
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何使用ndk-build.cmd构建Android.so文件
- libssh 的函数在构建 libssh 时无法在 Qt 和 cmake 错误中找到
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 我正在尝试使用 c++ 创建一个货币转换程序,我不知道如何继续
- C++嵌套if语句,基本货币交换
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 无法使用Qt Creator在Windows中构建yaml-cpp
- 构建一个由C和C++文件组成的库
- llvm构建器向基本块添加终止符
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- 如何跨平台将二进制资源构建到程序中?
- 将 OpenCV 与 CMAKE 中的项目一起构建为第三方库的正确方法
- 如何解决 Ninja c++ 构建和执行问题
- 使用 cmake 的 LLVM 构建在 tsan_libdispatch_mac.cc 期间失败; "Error: conflicting types for ..."
- CMake WxWidgets项目成功地在Linux上构建,但没有在Windows上构建
- 系统::货币和C 构建器