percision in c

1.120448
1.139124
1.194763

I am getting the output as above and want to truncate and save it as 1.1 in each case, so which function should i use..
1
2
3
4
5
6
double truncate(double x, double precision)
{                       // x = 1.120448
  x /= precision;       // x = 11.20448
  x = floor(x);         // x = 11.0
  return x * precision; // x = 1.1
}


floor() is from <math.h>.

Usage:
double y = truncate( 1.120448, 0.1 );

You might be able to do something simpler with fmod or modf, but I didn't see anything off the top of my head.
http://www.cplusplus.com/reference/cmath/modf/
http://www.cplusplus.com/reference/cmath/fmod/
Last edited on
Using modf:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>
#include <math.h>

double trunc_to_tenth(double param)
{
  double result, intpart;
  modf(modf(param, &result) * 10, &intpart);
  return result + (intpart / 10);
}

int main()
{
  double result, dval;
  
  dval = 1.120448;
  result = trunc_to_tenth(dval);
  printf("\nValue %f truncated to tenth place is: %f",dval,result);
  
  dval = 1.139124;
  result = trunc_to_tenth(dval);
  printf("\nValue %f truncated to tenth place is: %f",dval,result);
  
  dval = 1.194763;
  result = trunc_to_tenth(dval);
  printf("\nValue %f truncated to tenth place is: %f",dval,result);
  
  printf("\n");
  return 0;
}

Modified version of trunc function which is capable of rounding to any precision. Using modf and logic mentioned above by Stewbond.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>
#include <math.h>

double truncate(double param, double precision)
{
  double result, intpart;
  modf(modf(param, &result) * (1 / precision), &intpart);
  return result + (intpart / (1 / precision));
}

int main()
{
  double result, dval;
  
  dval = 1.120448;
  result = truncate(dval, 0.001);
  printf("\nValue %f truncated to tenth place is: %f",dval,result);
  
  dval = 1.139124;
  result = truncate(dval, 0.001);
  printf("\nValue %f truncated to tenth place is: %f",dval,result);
  
  dval = 1.194763;
  result = truncate(dval, 0.001);
  printf("\nValue %f truncated to tenth place is: %f",dval,result);
  
  printf("\n");
  return 0;
}

Topic archived. No new replies allowed.