Search code examples
c#tostringrect

How to convert a Rect ToString, while limiting decimal places?


Is there a simple format provider that will return a Rect structure ToString and limit the number of decimal places?

System.Windows.Rect myRect;

If I use myRect.ToString(), it returns

myRect: 0.0139211136847734,0.109375,0.995359599590302,1

I want this, limiting numbers to two decimal places but myRect.ToString("D2") does not compile

 myRect: 0.01,0.10,0.99,1

Note: I don't care about rounding, rounded or truncated is fine.


Solution

  • You could create an extension method:

    public static class RectExtensions
    {
        public static string ToStringRounded(this System.Windows.Rect rect)
        {
            return string.Format("{0},{1},{2},{3}", 
                Math.Round(rect.X, 2), Math.Round(rect.Y, 2), 
                Math.Round(rect.Width, 2), Math.Round(rect.Height, 2));
        }
    }
    

    and then call myRect.ToStringRounded();

    Don't forget to include the namespace of the extension method