2

In Matlab there is a function called int16, that rounds e.g. double values to the next integer. Is there any simple equivalent in C to that?

Especially for the rounding of negative numbers, e.g. -1.65 to -2 and 1.33 to -1.

Alex
  • 155
  • 1
  • 2
  • 10
  • 1
    Possible duplicate of [Is there a function to round a float in C or do I need to write my own?](http://stackoverflow.com/questions/497018/is-there-a-function-to-round-a-float-in-c-or-do-i-need-to-write-my-own) – samgak Sep 08 '16 at 06:31
  • Don't know how can it be duplicate of that one. The other question is about rounding the string representation, not converting a float to integer and round it (ceil or floor). – LoPiTaL Sep 08 '16 at 06:49
  • 1
    @LoPiTaL: The question asks about rounding the float value; the selected answer deals with printing it, but other answers talk about rounding. – Jonathan Leffler Sep 08 '16 at 07:10

1 Answers1

4

The int16 function, rounds and clamps the values. So an equivalent would look like this

int16_t  int16( double d ) 
{
  return isnan(d) ? 0 : (d > 32767.0) ? 
    32767 : 
    (d <-32768.0) ? -32768 : (int16_t)round(d)) ;
}

EDIT: int16 also returns 0 for NAN input, so handle this as well.

Also note, that the code really needs the case differentiations, as the conversion of double to int16_t in C is undefined for NAN and values outside of the range of the target integer.

Andreas H.
  • 5,557
  • 23
  • 32