Round Numbers

The C library holds functions that help you round-off floating point values. I can name a few, but then it would make this month’s rounding exercise too easy. So I won’t!

Rounding is a science. It involves three approaches:

  • To round up, you simply take any fraction over a integer and jump to the next highest integer.
  • To round down, you take any fraction over a integer and ignore it.
  • To round halfsies (my term) you evaluate the fractional part and if it’s under or over 0.5 you round up or down, respectively.

The issue of how to deal with 0.5 exactly is a source of debate, a topic I don’t want to get into.

For this month’s Exercise, you are to craft your own rounding functions. Two floating point values are given in the code skeleton, shown below. Your job is to round those values straight up, straight down, or split the rounding based on the fractional part of the number. You make that happen by filling in code for the roundup(), rounddown(), and roundhalf() functions.

#include <stdio.h>

float roundup(float n)
{
}

float rounddown(float n)
{
}

float roundhalf(float n)
{
}

int main()
{
    float v1,v2;

    v1 = 1234.56789;
    v2 = 98765.4321;

    printf("Value v1 = %f\n",v1);
    printf("Value v2 = %f\n",v2);
    printf("Rounded up:\t%f\t%f\n",
            roundup(v1),
            roundup(v2));
    printf("Rounded down:\t%f\t%f\n",
            rounddown(v1),
            rounddown(v2));
    printf("Rounded half:\t%f\t%f\n",
            roundhalf(v1),
            roundhalf(v2));

    return(0);
}

Here’s a major hint, which I’m providing gratis because I’m forbidding you from using any existing C library functions to handle the rounding process: You can easily lop off the fractional part of a floating point variable by typecasting it to an int.

Also, once you figure out the roundup() function, doing rounddown() is a snap. And then doing the roundhalf() function is equally as easy.

Click here to view my solution, although I recommend that you first try to solve the puzzle on your own.