Master117
Master117

Reputation: 659

Rounding Doubles to int C#

I want to calcuate the distance of a BorderControl to the Grid in which it is added, but in rounded percentage.

I use this method:

internal static tPosition GetControlTPosition(Border tempInnerControl, Grid tempOuterGrid)
    {
        tPosition tempTPosition = new tPosition();

        Point tempInnerControlCornerPoint = tempInnerControl.PointToScreen(new Point(0, 0));

        Point tempOuterGridCornerPoint = tempOuterGrid.PointToScreen(new Point(0, 0));

        //
        //Top Left Corner
        //Fist we calculate the Distance of the Top left Corners of both elements
        double distanceLeft = tempInnerControlCornerPoint.X - tempOuterGridCornerPoint.X;
        double distanceTop = tempInnerControlCornerPoint.Y - tempOuterGridCornerPoint.Y;

        //Then we set the percentage of our position accordingly
        tempTPosition.PositionLeft = (int)(((distanceLeft) * 100 / tempOuterGrid.ActualWidth));
        tempTPosition.PositionTop = (int)((distanceTop) * 100 / tempOuterGrid.ActualHeight);

        //
        // Bottom Right Corner
        //Now we calculate the distance of the bottom right corner to the outher grids bottom right corner
        double distanceRight =  (tempOuterGridCornerPoint.X + tempOuterGrid.ActualWidth) - (tempInnerControlCornerPoint.X + tempInnerControl.ActualWidth);
        double distanceBottom = (tempOuterGridCornerPoint.Y + tempOuterGrid.ActualHeight) - (tempInnerControlCornerPoint.Y + tempInnerControl.ActualHeight);

        tempTPosition.PositionRight = (int)((distanceRight)*100/tempOuterGrid.ActualWidth);
        tempTPosition.PositionBottom = (int)((distanceBottom) * 100 / tempOuterGrid.ActualHeight);

        return tempTPosition;
    }

My problem is that the BorderControl keeps getting bigger, meaning there is a problem with the percentages being to low, i guess this happen because i lose precision. How can i avoid this?

I need the numbers as int, for various reasons.

tPosition is just left,top,right,bottom as ints

Upvotes: 0

Views: 255

Answers (1)

DBull
DBull

Reputation: 86

You most likely lose your precision when finding tempTPosition, instead of using double as you have been you are using int, which will round the value to a whole number

try it with doubles

//Then we set the percentage of our position accordingly
    tempTPosition.PositionLeft = (double)(((distanceLeft) * 100 / tempOuterGrid.ActualWidth));
    tempTPosition.PositionTop = (double)((distanceTop) * 100 / tempOuterGrid.ActualHeight);

Remember to also do this for PositionRight & PositionBottom

Upvotes: 1

Related Questions