romanoza
romanoza

Reputation: 4862

System.Double type in Windows.Foundation.Size.Width / .Height on WinRT

I have a problem with the assignment of a value of double type on WinRT.

The following code:

Windows.Foundation.Size size = new Windows.Foundation.Size();
double v = 179.166660308838;
double v2 = v;
size.Width = v;
string t = $"v: {v}, v2: {v2}, size.Width: {size.Width}";

returns v: 179.166660308838, v2: 179.166660308838, size.Width: 179.166656494141. As you can see the values of v2 and size.Width are different.

My questions are:

Upvotes: 2

Views: 283

Answers (1)

RavingDev
RavingDev

Reputation: 2987

As it was mentioned by Hans Passant in comments "The underlying storage type for Size's properties is float, not double. A float can only round-trip 6 significant digits, if you display more of them then you'll see random noise digits." (Documentation)

You can check it using reflection:

        var sizeFields = typeof(Windows.Foundation.Size).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Select(f => $"{f.Name} - {f.FieldType.Name}");
        Debug.WriteLine(String.Join(", ", sizeFields));

And in output you will see _width - Single, _height - Single

If you disassemble System.Runtime.WindowsRuntime.dll you will see this code in constructor:

public Size(double width, double height)
{
  if (width < 0.0)
    throw new ArgumentException("width");
  if (height < 0.0)
    throw new ArgumentException("height");
  this._width = (float) width;
  this._height = (float) height;
}

Upvotes: 2

Related Questions