5

Possible Duplicate:
C# (4): double minus double giving precision problems

86.25 - 86.24 = 0.01

generally, I would think the above statement is true right?

However, if I enter this

        double a = 86.24;
        double b = 86.25;
        double c = b - a;

I find that c = 0.010000000000005116

Why is this?

Community
  • 1
  • 1
Diskdrive
  • 18,107
  • 27
  • 101
  • 167

2 Answers2

7

Floating point numbers (in this case doubles) cannot represent decimal values exactly. I would recommend reading David Goldberg's What every computer scientist should know about floating-point arithmetic

This applies to all languages that deal with floating point numbers whether it be C#, Java, JavaScript, ... This is essential reading for any developer working with floating point arithmetic.

As VinayC suggests, if you need an exact (and slower) representation, use System.Decimal (aka decimal in C#) instead.

Kobi
  • 135,331
  • 41
  • 252
  • 292
James Kovacs
  • 11,549
  • 40
  • 44
  • Since you mention various programming languages, I must point out that Ada is unique in allowing you to specify the desired precision of your reals (e.g. type Happiness is digits 7 range 0.0 .. 1.0`), and also in allowing fixed precision real values, such as `type Compass_Direction is delta 0.1 0 .. 359.9` which don't vary their precision at all across their range. – TamaMcGlinn Oct 13 '20 at 15:48
1

Double is incorrect data type for decimal calculations, use Decimal for that. Main reason lies in how double stores the number - its essentially a binary approximation of the decimal number.

VinayC
  • 47,395
  • 5
  • 59
  • 72