0

I'm looking for function which can Round off a float value in C ,Suppose have number 0.1153846 should be rounded off till 6 decimal producing output as 0.115385

Though there is function in objective c like lroundf() but not sure how can use it in my context.

I'm on gcc compiler and any help would be much appreciated.

Amit Singh Tomar
  • 8,380
  • 27
  • 120
  • 199
  • 2
    possible duplicate of [round() for float in C++](http://stackoverflow.com/questions/485525/round-for-float-in-c) – Tony The Lion Sep 14 '12 at 09:25
  • 1
    Not a good duplicate: This post is interested in rounding to a number of decimal places (6). Suggested [dupe](http://stackoverflow.com/questions/485525/round-for-float-in-c) is for rounding to a whole number. There are subtle and important different issues involved. – chux - Reinstate Monica Jan 29 '16 at 18:08

4 Answers4

1
float f = 0.1153846;
f = floor(f * 1000000) / 1000000;

This should work.

User 99x
  • 1,011
  • 1
  • 13
  • 39
1

You might want to do

  double x = 0.1153846;
  double rx = round (x * 1e6) * 1.e-6;

However, remember that IEEE 754 floating points are binary, with base 2 mantissa.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

It's quite unusual for float to be a decimal type, that means that whatever you do, the result of the rounding will most often than not not be representable in a float and will be adjusted again to match a representable number.

If such a rounding is really needed for computational purpose, a floating point type is probably not the correct type to use.

If it is just for display purpose, use the control the printf family give you.

AProgrammer
  • 51,233
  • 8
  • 91
  • 143
1
int precision = 3;
float num = 1.63322;
printf("%.*f",precision,num);
josliber
  • 43,891
  • 12
  • 98
  • 133
aman
  • 11
  • 1