Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [Quick Tip] Dealing with monetary values
Index -> General Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: 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;
}
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> General Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: