键入 C++ 中的大货币值
我应该在 C++ 中使用什么类型来存储像 5231451.3245114414 这样的大货币值?它应该允许存储 10 位甚至更多的十进制数字。
What type should i use in C++ to store large currecy values like 5231451.3245114414? It should allow to store 10 or even more decimal digits.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这取决于您的值有多大,更重要的是取决于所需的精度。
如果所有数字都具有相同的精度和小数位数,例如小数点后 10 位且不大于一百万,那么您可以只使用长整数(将所有数字乘以 1010 等)。
如果您确实需要任意比例和精度,那么您将无法绕过任意精度库。快速搜索发现了 mpdecimal,但可能还有其他。将定点方法与任意精度相结合,您还可以仅将 libgmp 用于任意精度整数,但将它们全部视为 1010 单位。
It depends on how large your values are, and more importantly on the required precision.
If all numbers have the same precision and scale, say 10 places after the decimal point and no bigger than one million, then you could just use long integers (multiply everything by 1010, etc.).
If you truly need arbitrary scales and precision, you won't get around an arbitrary-precision library. A quick search turned up mpdecimal, but there may be others. Combining the fixed-point approach with arbitrary precision, you could also just use libgmp for arbitrary-precision integers but treat them all as units of 1010.
您可能需要一个模仿 Java 的 BigDecimal 功能的自定义类型。
64 位双精度数只能精确到 17 位,因此您必须做得更好。
You probably need a custom type that mimics what Java's BigDecimal does.
A 64-bit double precision number is only accurate to 17 digits, so you'll have to do better than that.
您可以尝试检查 GMP 是否适合您的需要。如果我没记错的话,它有一个 C++ 包装器。
You may try to check if GMP suits what you need. It got a C++ wrapper if I remember correctly.
如果您必须使用货币值,您可能需要定点小数类,例如 这应该可以解决问题。
由于您想要所有的精度(出于好奇:为什么您需要货币金额?)您可能应该使用 64 位整数作为其基本类型(它应该足以容纳最多约 18 位十进制数字)。如果这还不够,您将不得不使用一些 biginteger 库来将任意大的整数作为定点十进制类的基础。
If you have to work with monetary values you probably want a fixed-point decimal class, so something like this should do the trick.
Since you want all that precision (out of curiosity: why do you need that for monetary amounts?) you should probably use a 64 bit integer as its base type (it should be enough for up to ~18 total decimal digits). If that still isn't enough you'll have to use some biginteger library to have an arbitrarily-big integer as the base for the fixed point decimal class.
你看过 decNumber++ 吗?链接可以在 http://speleotrove.com/decimal/ 找到?
Have you looked at decNumber++? Link can be found at http://speleotrove.com/decimal/ ?
谢谢大家的回答。我自己找到了最合适的解决方案。这只是一个文件,可以完成我需要的一切 - OLE 自动化类型 DECIMAL 的 C++ 包装类。它真的很轻(没有额外的繁重的库或文件)并且功能强大,可以处理非常大的数字。
Thanks you all for your answers. I found the most appropriate solution myself. It's just one file that does everything i need - C++ wrapper class for the OLE Automation type DECIMAL. It's really light (no additional heavy libraries or files) and powerfull and can handle REALLY BIG numbers.