C Round Function
It’s really weird that the C math library (math.h) doesn’t support the round function. It only includes the floor function which rounds down a float to an integer (can also be done by implicit or explicit casting) and the ceil function which rounds the value up.
For example,
int x; x = floor(1.2); // x is set to 1 x = floor(1.8); // x is set to 1 x = (int)1.8; // x is set to 1 (Explicit Narrowing Conversion) x = 1.8; // x is set to 1 (Implicit Narrowing Conversion) x = ceil(1.2); // x is set to 2 x = ceil(1.8); // x is set to 2
The round function is supposed to round the float value to the nearest integer.
x = round(1.2); // x is set to 1 x = round(1.8); // x is set to 2
This can be done adding a 0.5 to the value and then truncating it.
x = (int)(1.2 + 0.5); // x is set to 1 x = (int)(1.8 + 0.5); // x is set to 2
We also have to take negative values into consideration by adding -0.5 and then truncating.
x = (int)(-1.2 - 0.5); // x is set to -1 x = (int)(-1.8 - 0.5); // x is set to -2
Thus, here is the resulting C function:
int round(double number)
{
return (number >= 0) ? (int)(number + 0.5) : (int)(number - 0.5);
}
Note that you might want to use long rather than int to include support for larger numbers and avoid integer overflow.
That’s it, pretty much primitive, but fun!
Enjoy!
Ali B

C# Regular Expression Helper
One component of an application I’m writing uses a lot of regular expressions. To be sure I was using the right regular expressions, I’ve created this simple tiny tool to help me learn and verify regular expressions against my input data. Nothing fancy, but it might help someone out there.
For example, it took me a little while trying to find the proper regular expression to match all comments (including those that are not closed) in an Xml file.
Download exe or source. I recommend using this tool with this cheat sheet. It’ll definitely speed up the learning curve.
Share this:
Like this:
WinForms
csharp
match
Regex
regular expression
xml comment