65.9K
CodeProject is changing. Read more.
Home

Shortcut for Rounding Floating-point Values

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.84/5 (9 votes)

Dec 17, 2015

CPOL
viewsIcon

9307

downloadIcon

121

A small bit of code to help shorten/clarify your code when you need to round (floor & ceiling) numbers

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 doubles or floats 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.