cfloating-pointrounding

Manually implementing a rounding function in C


I have written a C program (which is part of my project) to round off a float value to the given precision specified by the user. The function is something like this

     float round_offf (float num, int precision)

What I have done in this program is convert the float number into a string and then processed it.

But is there a way to keep the number as float itself and implement the same.

Eg. num = 4.445 prec = 1 result = 4.4


Solution

  • Of course there is. Very simple:

    #include <math.h>
    
    float custom_round(float num, int prec)
    {
        int trunc = round(num * pow(10, prec));
        return (float)trunc / pow(10, prec);
    }
    

    Edit: it seems to me that you want this because you think you can't have dynamic precision in a format string. Apparently, you can:

    int precision = 3;
    double pie = 3.14159265358979323648; // I'm hungry, I need a double pie
    printf("Pi equals %.*lf\n", precision, pie);
    

    This prints 3.142.