rounding and var-to-integer conversions

Posted By: pfeldman

rounding and var-to-integer conversions - 09/21/08 03:38

When I search the manual, I can find nothing on the following two topics:

(1) rounding: I'd like to be able to round a var to the nearest integer, round down to the nearest integer (floor), or round up to the nearest integer (ceil).

(2) conversion from var to int or from var to short: It would be nice to be able to do such conversions, either via type cast, or by calling a function.

Adding such functions would be a major benefit.
Posted By: Spirit

Re: rounding and var-to-integer conversions - 09/21/08 09:19

(1) int round(var x) { return (int)(x + 0.5*sign(x)); }

(2) int i = x; short s = x;

Posted By: FBL

Re: rounding and var-to-integer conversions - 09/21/08 10:33

(1) use the integer() function

(2) var <-> int is automatically converted. Forcing a cast will deliver undesired results as the fixpoint value of var won't be converted to int as you'd expect.
Posted By: pfeldman

Re: rounding and var-to-integer conversions - 09/21/08 20:09

OK. Thanks to both of you!

I can't find any mention of the round() function in the online manual.
Posted By: Scorpion

Re: rounding and var-to-integer conversions - 09/21/08 21:33

It's because there is no round function there. Just use the one Spirit posted

Well and here is the ceil function 4 you wink
Code:
int ceil(var x) { return (int)(x+1); }

Posted By: FBL

Re: rounding and var-to-integer conversions - 09/21/08 22:15

of course there is a round function... As I posted above: integer()
Posted By: jcl

Re: rounding and var-to-integer conversions - 09/22/08 07:31

No, integer() does not round. It just removes the fractional part of the number. For rounding and ceil use the functions posted by Spirit and Scorpion.
© 2024 lite-C Forums