Search code examples
c#floating-pointrounding-error

double rounding error without calculation


I observed a (for me) strange issue in C# (.Net 4.6.1) with floating-point variables.

I have an own simple Point class:

public class Point
{
    public readonly double X;
    public readonly double Y;


    public Point(double x, double y)
    {
        this.X = x;
        this.Y = y;
    }

    //...

}

And a Rectangle class with Contains-method. Sometimes - very hard to reproduce - when I pass a Point object to Contains method of a Rectangle object the values of X or Y are not the same. There is no calculation between or any other change of the variable. Just getting the variable value. In the caling method the value is OK and inside the called method the value has a rounding error.

calling the Contains method

inside the called Contains method

What is the problem here? Why is there another value inside the called method?

At the end the value is not changing. So in the caller method the value is still OK later.

Thanks in advance!

Maas


Solution

  • OK, it was my mistake. I presumed that ToString method of Point is showing the complete value. Normally it does.

    public override string ToString()
    {
        return $"{this.X};{this.Y}";
    }
    

    The value has a rounding error in the caller method too.