开发者

Type for large currency values in C++

开发者 https://www.devze.com 2023-04-06 00:44 出处:网络
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.It depends on how large your values are, and

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.


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.


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.


You may try to check if GMP suits what you need. It got a C++ wrapper if I remember correctly.


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.


Have you looked at decNumber++? Link can be found at http://speleotrove.com/decimal/ ?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号