Introduction
Have you ever had to round a number to put it in an integer variable and wondered how inconvenient it is that Math.Round
and others return a double
instead of an integer? Casting the result to int
isn't that long, but when you need to round multiples values to create an object (e.g., a rectangle), you are then forced to do something similar (which takes up quite a lot of space):
return new Rectangle(
(int)Math.Round(floatX),
(int)Math.Round(floatY),
(int)Math.Round(floatWidth),
(int)Math.Round(floatHeight));
Using the Code
I created three structs: ROUND
, CEIL
and FLOOR
. They need to be explicitly casted from double
s or float
s values, but are implicitly casted into int
.
return new Rectangle(
(ROUND)floatY,
(ROUND)floatX,
(ROUND)floatWidth,
(ROUND)floatHeight);
int myIntValue = (CEIL)floatVal;
myIntValue = (FLOOR)floatVal;
Points of Interest
It is really amazing what you can do with operator overloading. While I knew the concept for long, it is only recently that I thought about this shortcut. I was developing a custom control and the drawing code required a lot of rounding and the code began to be filled with (int)Math.Round
.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.