0

Most C compilers offer some variation of the Standard C Library. The VisualDSP++ compiler is no different. However, I've recently encountered a scenario where I need to take a float value, round it to the nearest whole number and then convert it to an int.

This is rather easy using most variations of C, but after attempting to use roundf, I've found that math.h does not include the roundf function.

How can I correctly round my float variables to the nearest int value with VisualDSP++?

RLH
  • 15,230
  • 22
  • 98
  • 182
  • For those who are unaware of VisualDSP, it is an embedded systems development IDE an compiler. – RLH Jun 19 '13 at 18:34
  • Would the strategy in [this answer](http://stackoverflow.com/a/497079/7116) work for you? – user7116 Jun 19 '13 at 18:37

2 Answers2

4

I am not familiar with VisualDSP, but you can round a float to an integer like so:

float number = 3.14;
int rounded = (int)(number + (number > 0 ? 1 : -1) * 0.5);

So, you could write your own function for this:

int roundFloatToInt(float number)
{
    return (int)(number + (number > 0 ? 1 : -1) * 0.5);
}

The above outputs the following for the given input:

roundFloatToInt(0.10) --> 0

roundFloatToInt(3.14) --> 3

roundFloatToInt(3.54) --> 4

It appears to work in all the cases I tested, including negatives.

1

The *f() functions, including roundf, were added in, as I recall, the 1999 version of the ISO C standard, along with the roundd function that operates on long doubles.

It's likely possible that your <math.h> declares round, which operates on double rather than float. (C90 actually didn't have any of round, roundf, or roundl, but your implementation might provide round as an extension.) (EDIT: No, it doesn't.)

Untested code follows:

float x = 123.456;
int n = round(x);

round takes a double argument; the float argument passed to it will be implicitly converted. The double result is then implicitly converted to int.

You could make all the conversions explicit by adding casts:

int n = (int)round((double)x);

but that's just clutter.

EDIT: C89/C90 did define the floor and ceil functions. If round isn't available, it shouldn't be difficult to define it in terms of floor. The details depend on exactly what kind of rounding you want to do.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • Sorry, I should have explained my thoroughness a bit better. I did a search throughout the entire VisualDSP++ application directory, which includes the include files and all internal C files. "round" doesn't exist as a function name or as part of one within the entire compilers internal library. – RLH Jun 19 '13 at 18:47
  • Regarding your EDIT post. There is a chance that this is a C89/90 compiler. I inherited this project and since my primary background is Windows development, I'm use to the "conveniences" of more modern compilers that are kept up-to-date. Visual C++ 6.0 is probably more current that VisualDSP++. – RLH Jun 19 '13 at 18:49