user1611753
user1611753

Reputation: 365

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

Upvotes: 1

Views: 4289

Answers (2)

Eregrith
Eregrith

Reputation: 4366

Yes:

float round_offf(float num, int precision)
{
  int result;
  int power;

  power = pow(10, precision + 1);
  result = num * power;
  if ((result % 10) > 5)
    result += 10;
  result /= 10;
  return ((float)result / (float)power);
}

Upvotes: -1

user529758
user529758

Reputation:

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.

Upvotes: 3

Related Questions