codescracker


c

C Program to Round off Decimal or Floating-point Number



« C Tutorial C Examples »

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

// Write a program in C, to read following numbers
// from your keyboard, round them to their nearest
// integer value and print the result in integer format
// For example, 37.5 to 38, 50.123 to 50, -25.5649 to -24
// -56.8877 to -55, and 123.0 to 123 etc.
// -----------codescracker.com-----------

#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;
}

As the above program was written under Code::Blocks IDE, therefore after successful build and run, you will get the similar output as given below. This is the first snapshot of the sample run:

c program round off integer

Now supply any real number say 37.5 and press 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 user has provided the real number say -25.56 as input:

rounding off to nearest value c program

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


« C Tutorial C Examples »






Tools
Calculator

Quick Links
Signup - Login - Give Online Test