Rounding Numbers (floats as signed ints)

Go To Last Post
7 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Perhaps it's because it's Friday afternoon - but I just can't get my head around this one.

How can I "round" numbers. E.g 40.4 = 40 and 40.5 = 41

I'm askign this because I want to store a float as a signed int. My float willl normally be between -200 and +200 so if I want 2.d.p accuracy.

So if my float was -14.267894 I would like to round this to -14.27 and then multiply by 100 so I can store it in an int as -1427.

All the alorgithms I can think up to do this seem far too complex.

Ben
-Using IAR (& ocasionally CodeVision)
0.7734
1101111011000000110111101101

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Don't you just add 0.5 (or, if the number is < 0, subtract 0.5) and then truncate, by casting to an int?

Four legs good, two legs bad, three legs stable.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You know what? - I think you might be right - perhaps I am thinking too hard (although my Boss might disagree).

Ben
-Using IAR (& ocasionally CodeVision)
0.7734
1101111011000000110111101101

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Alternative:

Quote:
double round(double);

C: i = "told you so";

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

cpluscon wrote:
Alternative:
Quote:
double round(double);

If your compiler has it. "round" is not a standard library function (though I'm not sure why it wouldn't have one).

Regards,
Steve A.

The Board helps those that help themselves.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Quote:
"round" is not a standard library function
I've always used floor(x+0.5) for this, but the round() implementation may be slightly more efficient. GCC has round() in math.h, but my MS C++ compiler doesn't....

http://cvs.savannah.nongnu.org/v...

C: i = "told you so";

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Similar to cpluscon, I've used trunc(x+(base_of_x/2)).

Mike Coles http://blips.net
'bluelip' http://diyaday.com