Click here to Skip to main content
15,891,529 members
Articles / Programming Languages / C#
Tip/Trick

Shortcut for Rounding Floating-point Values

Rate me:
Please Sign up or sign in to vote.
4.84/5 (9 votes)
17 Dec 2015CPOL 9K   121   4   3
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):

C#
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.

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionOr you could have written them as extension methods Pin
John Brett18-Dec-15 0:38
John Brett18-Dec-15 0:38 
GeneralRe: Or you could have written them as extension methods Pin
  Forogar  18-Dec-15 4:14
professional  Forogar  18-Dec-15 4:14 
Praisebest thing sliced bread Pin
CaldasGSM17-Dec-15 8:06
CaldasGSM17-Dec-15 8:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.