how to represent a monetary type in C++?

Hi,

No, I don't think using double is enough because the decimal part is an approximation in double. What I am looking is for a type that models monetary amounts with absolute precision (thus must be implemented by an underlying long long for instance). There must be a library out there that does this. Any pointers?
maybe a boost library?

Regards,
Juan Dent
Basically three options:
1. Store cents in std::int64_t.
2. Store monetary units in a rational type composed of two std::int64_t values. So 1 unit is 1/1, one cent is 1/100, and one tenth of a cent is 1/1000.
3. Use a decimal floating point library.

https://software.intel.com/content/www/us/en/develop/articles/intel-decimal-floating-point-math-library.html
https://github.com/libdfp/libdfp
Last edited on
or a slight variation on 2, is an object with 2 fields, eg

struct munny{unsigned long long dollars; unsigned long long cents;}
where the fractional part is implied by its struct member name and how you will use it.

honestly #1 seems to me to be the way to go, and if it won't fit you are in a system large enough that you can afford to buy a 128 bit machine (there are a few with 128 bit register(s) even if 64 bit memory addressed etc) or a bigint class.

a couple of things to mind: how do you want to handle conversion to other currencies? How do you want to handle fractions of cents for interest calculations? What else do you need to worry about that involves floating point?

The thing about a fixed point representation is that you have to set ahead of time how much precision you want, and if you end up needing more at some point, you may be kind of screwed.
Personally I like rationals, but they're not without their issues. If your operations deal with a lot of coprime denominators (which in monetary applications is unusual anyway) your values can overflow easily, and dealing with overflowed rationals (or mitigating overflows) is not easy.
Decimal floating point is basically set-and-forget, but you do need to add an external dependency.
Topic archived. No new replies allowed.