What is the best data type to use for currency in C#?


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. To initialize a decimal variable, use the suffix m or M.

decimal b = 2.1m;

The below example shows the min and max value of decimal.

Example

 Live Demo

using System;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         Console.WriteLine($"Deciaml Min Value: {decimal.MinValue}");
         Console.WriteLine($"Deciaml Max Value: {decimal.MaxValue}");
         Console.ReadLine();
      }
   }
}

Output

Deciaml Min Value: -79228162514264337593543950335 

Deciaml Max Value: 79228162514264337593543950335


The finite set of values of type decimal are of the form (-1)^s * c * 10^-e, where the sign s is 0 or 1, the coefficient c is given by 0 <= *c* < 2^96, and the scale e is such that 0 <= e <= 28.The decimal type does not support signed zeros, infinities, or NaN's. A decimal is represented as a 96-bit integer scaled by a power of ten. For decimals with an absolute value less than 1.0m, the value is exact to the 28th decimal place, but no further.

For decimals with an absolute value greater than or equal to 1.0m, the value is exact to 28 or 29 digits. Contrary to the float and double data types, decimal fractional numbers such as 0.1 can be represented exactly in the decimal representation. In the float and double representations, such numbers are often infinite fractions, making those representations more prone to round-off errors.

Decimal type is preferred over float and double because it has more precision and a smaller range than both float and double.

Example

Let us consider an example where US dollar is converted to Indian Rupee.

 Live Demo

using System;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         decimal usd = 2.5m;
         Console.WriteLine($"USD: {usd}");
         decimal inrOfOneUSD = 75.04m;
         Console.WriteLine($"INR value of one USD: {inrOfOneUSD}");
         decimal inr = usd * inrOfOneUSD;
         Console.WriteLine($"INR value: {inr}");
         Console.ReadLine();
      }
   }
}

Output

The output of the above code is

USD: 2.5
INR value of one USD: 75.04
INR value: 187.600

Updated on: 19-Aug-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements