Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data type should I use to represent money in C#?

Tags:

c#

In C#, what data type should I use to represent monetary amounts? Decimal? Float? Double? I want to take in consideration: precision, rounding, etc.

like image 807
A Salcedo Avatar asked Jun 17 '09 18:06

A Salcedo


People also ask

What type of data is currency?

A data type used to declare variables capable of holding fixed-point numbers with 15 digits to the left of the decimal point and 4 digits to the right. Due to their accuracy, Currency variables are useful within calculations involving money.

What data type should you use to represent the amount of money you have?

The money data type is an abstract data type. Money values are stored significant to two decimal places. These values are rounded to their amounts in dollars and cents or other currency units on input and output, and arithmetic operations on the money data type retain two-decimal-place precision.

Which choice is the best data type for working with money?

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.


2 Answers

Use System.Decimal:

The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations requiring large numbers of significant integral and fractional digits and no round-off errors. The Decimal type does not eliminate the need for rounding. Rather, it minimizes errors due to rounding.

Neither System.Single (float) nor System.Double (double) are precise enough capable of representing high-precision floating point numbers without rounding errors.

like image 134
Andrew Hare Avatar answered Oct 13 '22 00:10

Andrew Hare


Use decimal and money in the DB if you're using SQL.

like image 23
Fiur Avatar answered Oct 12 '22 23:10

Fiur