Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What class to use for money representation?

What class should I use for representation of money to avoid most rounding errors?

Should I use Decimal, or a simple built-in number?

Is there any existing Money class with support for currency conversion that I could use?

Any pitfalls that I should avoid?

like image 477
Esteban Küber Avatar asked Sep 10 '09 17:09

Esteban Küber


People also ask

What data type should you use for currency?

The best datatype to use for currency in C# is decimal. The decimal type is a 128-bit data type suitable for financial and monetary calculations. The decimal type can represent values ranging from 1.0 * 10^-28 to approximately 7.9 * 10^28 with 28-29 significant digits.

What data type should I use for money in Java?

1 Answer. Java has Currency class that represents the ISO 4217 currency codes. BigDecimal is the best type for representing currency decimal values.

Should you use float for money?

Float & Double are bad for financial (even for military use) world, never use them for monetary calculations. If precision is one of your requirements, use BigDecimal instead.

What data type is money in Python?

Python's float type is a natural first step to represent monetary amounts in the code. Almost all platforms map Python floats to IEEE-754 “double precision”.


1 Answers

Never use a floating point number to represent money. Floating numbers do not represent numbers in decimal notation accurately. You would end with a nightmare of compound rounding errors, and unable to reliably convert between currencies. See Martin Fowler's short essay on the subject.

If you decide to write your own class, I recommend basing it on the decimal data type.

I don't think python-money is a good option, because it wasn't maintained for quite some time and its source code has some strange and useless code, and exchanging currencies is simply broken.

Try py-moneyed. It's an improvement over python-money.

like image 119
Thiago Chaves Avatar answered Oct 03 '22 19:10

Thiago Chaves