C Program to Round Off a Decimal or Floating-Point Number

In this tutorial, we will learn how to create a program in C that will ask the user to enter any number (any real or floating-point number) to round it off to the nearest integer. For example, if the user has provided 23.43 as input, then the program will output its nearest integer value, which will be 23. Let's take a look at the program:

#include<stdio.h>
#include<conio.h>
int main()
{
    float num;
    int tempCheck, roundNum, tempNum;
    printf("Enter the number: ");
    scanf("%f", &num);
    if(num>0)
    {
        tempNum = num*10;
        tempCheck = tempNum%10;
        if(tempCheck>=5)
        {
            roundNum = num;
            roundNum++;
        }
        else
        {
            roundNum = num;
        }
        printf("\nWhole number after rounding off the given real number = %d", roundNum);
    }
    else if(num<0)
    {
        num = -(num);
        tempNum = num*10;
        tempCheck = tempNum%10;
        if(tempCheck>=5)
        {
            roundNum = num;
            roundNum--;
        }
        else
        {
            roundNum = num;
        }
        printf("\nWhole number after rounding off the given real number = -%d", roundNum);
    }
    else
    {
        printf("\nThe given number is 0");
    }
    getch();
    return 0;
}

Because the above program was written in the Code::Blocks IDE, the output will be similar to the one shown below after a successful build and run. This is the first snapshot of the sample run:

c program round off integer

Now supply any real number, say 37.5, and press the ENTER key to see the nearest integer (whole number) value of the given real number:

round off to nearest integer

Here is another sample run of the above program; this time let's suppose the user has provided the real number, say -25.56, as input:

rounding off to nearest value c program

Here is a list of some of the main steps used in the above program:

C Quiz


« Previous Program Next Program »


Liked this post? Share it!