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

In C #, what type of data should I use to represent monetary amounts? Decimal? Float? To double? I want to take into account: precision, rounding, etc.

+46
c #
Jun 17 '09 at 18:35
source share
6 answers

Use System.Decimal :

The decimal value type represents decimal numbers 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 type of decimal value is suitable for financial calculations requiring a large number of significant integral and fractional digits and without rounding errors. Decimal type does not eliminate the need for rounding. Rather, it minimizes round-off errors.

Neither System.Single ( float ) nor System.Double ( double ) quite accurate Able to display floating point numbers with no rounding errors.

+68
Jun 17 '09 at 18:36
source share
— -

Use decimal and money in the database if you are using SQL.

+4
Jun 17 '09 at 18:39
source share

Decimal is the one you want.

+3
Jun 17 '09 at 18:37
source share

In C #, the Decimal type is actually a structure with overloaded functions for all math and comparison operations in base 10, so it will have less significant rounding errors. A float (and double), on the other hand, is akin to scientific notation in binary format. As a result, decimal types are more accurate when you know the precision you need.

Run this to see the difference in accuracy 2:

 using System; using System.Collections.Generic; using System.Text; namespace FloatVsDecimal { class Program { static void Main(string[] args) { Decimal _decimal = 1.0m; float _float = 1.0f; for (int _i = 0; _i < 5; _i++) { Console.WriteLine("float: {0}, decimal: {1}", _float.ToString("e10"), _decimal.ToString("e10")); _decimal += 0.1m; _float += 0.1f; } Console.ReadKey(); } } } 
+2
Jun 17 '09 at 18:54
source share

Consider using Money Type for the CLR . This is a custom value type (struct) that also supports currencies and handles rounding problems.

0
Dec 19 '14 at 8:57
source share

In C #, you have to take " Decimal " to represent monetary amounts.

0
Apr 26 '16 at 8:19
source share



All Articles