[Question] What is the Main Difference of Float, Double and Decimal Types in C#?

Answer

The main difference of Float, Double and Decimal is precision. Decimals have a high degree of accuracy.

Unlike decimals, floats/doubles types have special values. The float and double have constants for NaN, +∞, and −∞, as well as other values (MaxValue, MinValue, and Epsilon).

Another significant difference is that float/double internally represent numbers in base 2, but decimal base 10.

Of course they have different sizes as well:

  • Float size is 32 bit (7 digits)
  • Double size is 64 bit (15-16 digits)
  • Decimal size is 128 bit (28-29 digits)

Details

Decimal numbers have much higher precision and are usually used within financial applications that require a high degree of accuracy. Decimals are much slower (20X times in some tests) than a double/float numbers.

Double is useful for scientific computations (such as computing spatial coordinates). Decimal is useful for financial computations and values that are “human-made” rather than the result of real-world measurements.

Decimals and floats/doubles cannot be compared without a cast whereas Floats and Doubles can. Decimals also allow the encoding or trailing zeros.

[adinserter block=”6″]

Examples

Code

Console.WriteLine ( 1.0 / 0.0); // Infinity
Console.WriteLine (−1.0 / 0.0); // -Infinity
Console.WriteLine ( 1.0 / −0.0); // -Infinity
Console.WriteLine (−1.0 / −0.0); // Infinity
Console.WriteLine ( 0.0 / 0.0); // NaN
Console.WriteLine ((1.0 / 0.0) − (1.0 / 0.0)); // NaN
Console.WriteLine (0.0 / 0.0 == double.NaN); // False
Console.WriteLine (double.IsNaN (0.0 / 0.0)); // True
Console.WriteLine (object.Equals (0.0 / 0.0, double.NaN)); // True

Code
float f = 1F / 9;
double d = 1D / 9;
decimal dc = 1M / 9;
Console.WriteLine("Float number example: {0}\nDouble number example: {1}\nDecimal number example: {2}", f, d, dc);

Result
Float number example: 0.11111111
Double number example: 0.1111111111111111
Decimal number example: 0.1111111111111111111111111111

Useful information

Decimal type exist only in c#

Test Environment

  • Windows 11
  • Visual Studio 2022
  • Visual Studio 2022
  • C# 9
  • .NET 5

Tags:,

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.