views:

559

answers:

4
+4  Q: 

Money Type

Does anyone know of an already implemented money type in the .net framework that supports i18n (currencies, formatting, etc)? I have been looking for a well implemented type and can't seem to find one.

+2  A: 

I think you want to use the decimal data type, and use the appropriate overload for ToString().

CultureInfo current  = CultureInfo.CurrentCulture;
decimal myMoney = 99.99m;

//formats as money in current culture, like $99.99
string formattedMoney = myMoney.ToString("C", current);
Jason Jackson
+4  A: 

Check this article A Money type for the CLR

A convenient, high-performance money structure for the CLR which handles arithmetic operations, currency types, formatting, and careful distribution and rounding without loss.

John
Very interesting. This would have helped on a past project of mine.
Jason Jackson
This was exactly what I was looking for! Thank you!
Mateo
+1  A: 

yeah... make sure you use the decimal type for money.

Float is NOT accurate for decimal values.

Atømix
A: 

i would use integer/long, and use a very low denomination like cents (or pence) - then there would be no decimal to work with, and all calculations can be rounded to the nearest cent.

or, take a look at Martin Fowler's book "Patterns of Enterprise Application Architecture". In that book, he talked about how to implement a money class. http://www.amazon.com/Enterprise-Application-Architecture-Addison-Wesley-Signature/dp/0321127420

Chii
You have it slightly wrong here. It's not a very low denomination, it's the lowest denomination. It's the only bulletproof answer I've ever found--if you have precision beyond reality you're going to get fractions carried after divisions that shouldn't be carried.
Loren Pechtel
The cent is not the lowest denomination in American currency, though; otherwise gas stations couldn't sell gas at $2.149/gal, which they do. Likewise, percentages (such as interest) often result in fractional cents, and rounding isn't always appropriate in intermediate steps.
technophile