Computer Science Canada

[Quick Tip] Dealing with monetary values

Author:  wtd [ Wed Mar 10, 2004 8:27 pm ]
Post subject:  [Quick Tip] Dealing with monetary values

I just answered a question on this subject in another forum and thought I'd share this bit of wisdom here.

When dealing with monetary values, it's very common to use floating point numbers to deal with amounts less than one dollar. However, floating point numbers have an inherent level of inaccuracy.

Instead, it's better practice to use integers to keep track of such values. So instead of keeping track of dollars, we can keep track of cents, or keep track of dollars and cents separately, bundled up in an object.

An example of how to handle this, in C++.

code:
#include <iostream>

struct Money {
   int dollars;
   int cents;

   Money(int init_dollars = 0, int init_cents = 0)
   : dollars(init_dollars)
   , cents(init_cents)
   { }

   int total_cents() {
      return dollars * 100 + cents;
   }
};

int main() {
   Money m(42, 23);
   std::cout << m.dollars << "." << m.cents << std::endl;
}


: