Round Numbers – Solution

This month’s Exercise required you to create three rounding functions: roundup(), rounddown(), and roundhalf(). Each one deals with a floating-point value in a specific way, but they all handle the basic rounding chore by typecasting a floating point variable to an integer.

Click here to view my solution. Your solution can be subtly different, as long as it yields the same results.

Here’s sample output:

Value v1 = 1234.567871
Value v2 = 98765.429688
Rounded up:	1235.000000	98766.000000
Rounded down:	1234.000000	98765.000000
Rounded half:	1235.000000	98765.000000

For my approach with the roundup() function, I typecast the function’s variable n as an integer at Line 7. That value is increased by one (to round “up”), and returned as a float in Line 8:

    r = (int)n;
    return( (float)(r+1) );

I could have split that process up into several lines, or I could have scrunched it all up into one. However it’s done, the result is the same.

In the rounddown() function, the integer typecast for variable n is simply returned:

    r = (int)n;
    return( (float)r );

Another way to do this, which is obfuscated but it works, is this:

    return( (float)((int)n) );

The first typecast, (int)n, must be enclosed in parentheses or the compiler gets all testy.

Finally, for the roundhalf() function, I inserted the typecasting technique for rounding down in Lines 24 and 25:

    r = (int)n;
    t = (float)r;

The purpose here is to get the round-down value of variable n into variable t. An alternative would have been to use the rounddown() function directly:

    t = rounddown(n);

Once you have that lower value in variable t, a simple comparison with 0.5 determines whether to round up or round down, and return the appropriate value:

    if( n - t < 0.5)
        return(t);
    else
        return(t+1);

In my rendition of the roundhalf() function, any value 0.5 or greater is always rounded up. You could modify the code to specifically deal with the exact value 0.5, determining when and how it gets rounded. I'll leave that chore up to you to experiment with on your own.