Update: C# Money/Currency Class

One of the more popular pages on my site is my C# implementation of a Money/Currency class. I had an excellent suggestion made to me that I finally got around to implementing.

In the previous implementation, the rounding for currency was performed internal to the class. So, if you were trying to divide a single USD by 8, you’d end up with $0.13 (not $0.125). This will work fairly well for many implementations, but the suggestion was to externalize the rounding and allow the item using the Money/Currency object to decide how any rounding would be performed (if at all).

A practical use for this is in curency exchange. Today’s exchange rate from USD to CAD is 1.12565. If I were to convert 50 USD to CAD would be a result of 56.2825, thus allowing the class to respect the decimal places of CAD, but force any implementation to account for how it wants to handle the reamining 0.0025.

e.g.
 

Money usDollars = new Money(50m, "en-us");

Money convertedCanadianDollars = new Money(usDollars.Amount * 1.12565m, "en-CA");

This accurately results in the convertedCanadianDollars to have an Amount of 50.2825.

Assert

.AreEqual(50 * 1.12565m, convertedCanadianDollars.Amount);

So, I have published the new version of the code for public consumption.

Advertisements

2 thoughts on “Update: C# Money/Currency Class

  1. Very nicely done.  Thanks for the update, J.
    P

  2. I ❤ jason hunt!!! wooo hooo!!!! nyahhhhhhh!!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s