Double in.net

If I have the following code (this was written in .NET)

double i = 0.1 + 0.1 + 0.1; 

Why is i not equal to 0.3 ?
Any ideas?

+2
source share
7 answers

You need to read floating point numbers. Many decimal numbers do not have an exact representation in binary format, so they will not exactly match.

That's why in comparison, you usually see:

 if (abs(ab) < epsilon) { ... 

where epsilon is a small value, such as 0.00000001, depending on the required accuracy.

+6
source

Double is a 64-bit floating point data type. It stores decimal numbers as approximate values. If you need accurate values, use the Decimal data type, which is the Binary Coded Decimal data type.

+3
source

The precision of floating point arithmetic cannot be guaranteed.

+1
source

Floating point equality is often not used because there is always a problem with the representation. We usually compare the difference between two floats and, if it is less than a certain value (for example, 0.0000001), it is considered equal.

+1
source

Double calculation is not accurate. You have two solutions:

  • Use the Decimal type, which is exact
  • Compare abs (i - 0.3) espilon
+1
source

Jon Skeet has a very good walkthrough for this here , and the same for decimal here .

+1
source

All Articles