Write a one line C function to round floating point numbers

Algorithm: roundNo(num)
1. If num is positive then add 0.5.
2. Else subtract 0.5.
3. Type cast the result to int and return.

Example:
num = 1.67, (int) num + 0.5 = (int)2.17 = 2
num = -1.67, (int) num – 0.5 = -(int)2.17 = -2

Implementation:

filter_none

edit
close

play_arrow

link
brightness_4
code

/* Program for rounding floating point numbers */
# include<stdio.h>
  
int roundNo(float num)
{
    return num < 0 ? num - 0.5 : num + 0.5;
}
  
int main()
{
    printf("%d", roundNo(-1.777));
    getchar();
    return 0;
}

chevron_right


Output: -2

Time complexity: O(1)
Space complexity: O(1)

Now try rounding for a given precision. i.e., if given precision is 2 then function should return 1.63 for 1.63322 and -1.63 for 1.6332.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.