Alex Rivera | Logout

decimal vs double! - Which one should I use and when?

Asked 2009-07-22T14:37:54.860
1044

I keep seeing people using doubles in C#. I know I read somewhere that doubles sometimes lose precision. My question is when should a use a double and when should I use a decimal type? Which type is suitable for money computations? (ie. greater than $100 million)

Edit
Report

1 Answer

51

According to Characteristics of the floating-point types:

.NET Type C# Keyword Precision
System.Single float ~6-9 digits
System.Double double ~15-17 digits
System.Decimal decimal 28-29 digits

The way I've been stung by using the wrong type (a good few years ago) is with large amounts:

  • £520,532.52 - 8 digits
  • £1,323,523.12 - 9 digits

You run out at 1 million for a float.

A 15 digit monetary value:

  • £1,234,567,890,123.45

9 trillion with a double. But with division and comparisons it's more complicated (I'm definitely no expert in floating point and irrational numbers - see Marc's point). Mixing decimals and doubles causes issues:

A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used because the floating-point number might not exactly approximate the decimal number.

When should I use double instead of decimal? has some similar and more in

answered 2010-02-04T12:06:45.613

Your Answer