2
\$\begingroup\$

Currently I have this code:

float tileX = (float)rectangle.X / (float)newTileSize;
float tileY = (float)rectangle.Y / (float)newTileSize;

int xOrigin = (int)Math.Round(tileX) * newTileSize;
int yOrigin = (int)Math.Round(tileY) * newTileSize;

// Same idea for the next 4 lines

float tileWidth = (float)rectangle.Width / (float)newTileSize;
float tileHeight = (float)rectangle.Height / (float)newTileSize;

int selectorWidth = (int)Math.Round(tileWidth) * newTileSize;
int selectorHeight = (int)Math.Round(tileHeight) * newTileSize;

The reason for the first two lines is because if I don't cast them as a float it does integer division and I was a floating point value instead so I can round it in the next two lines.

This code is fine I guess it just seems like there would be a better way to do it without so much casting. Just seems rather verbose if that makes any sense.

Thanks.

\$\endgroup\$
2
\$\begingroup\$

So you're looking for

int result = (int)Math.round((float)n/(float)d) * d;

(assuming you are only interested in the intermediate values for this particular calculation)

Here's a test case with an alternative:

import junit.framework.TestCase;

public class TestModulo extends TestCase {

    private final static int d = 7;

    public void testModulo() throws Exception {
        for (int n = 0; n < 30; n++) {
            assertEquals("fails for " + n, f2(n), f1(n));
        }
    }

    private int f1(int n) {
        return (int) Math.round((float) n / (float) d) * d;
    }

    private int f2(int n) {
        return ((n + d / 2) / d) * d;
    }

}

You can solve your problem using only integer math.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Much obliged =) \$\endgroup\$ – John Smith Aug 18 '11 at 18:03
1
\$\begingroup\$

The reason for the first two lines is because if I don't cast them as a float it does integer division and I was a floating point value instead so I can round it in the next two lines.

Well, you only need to cast one side to get a float as the return value.

float tileX = (float)rectangle.X / newTileSize;
float tileY = (float)rectangle.Y / newTileSize;

Because you are working with the System.Drawing.Rectangle type there is really no other way to go about it. All of the properties are ints, and you need to perform floating point arithmetic, so a cast is required. You could of course assign the X and Y values to a float first, but that doesn't save you anything. This is very common when working with graphics in WinForms.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.