NO

Author Topic: float to int conversion  (Read 3538 times)

Franzki

  • Guest
float to int conversion
« on: June 24, 2009, 10:01:19 AM »
Float-to-integer conversion in C can be done like this:

Code: [Select]
int i;
float f;

f=27.35;
i=(int)(f);

As far as I know C's floating to integer conversion truncates (discards) the fractional part. This leaves the integer part of the float as result.

In the Pelles 6.0 help (the part about the microsoft extensions compiler switch) there are 2 ways of float-to-integer conversions mentioned... chopping and limiting. Can someone tell me the difference as it's not really clear to me.

nicolas.sitbon

  • Guest
Re: float to int conversion
« Reply #1 on: June 24, 2009, 10:21:52 AM »
The standard says:
Quote
6.3.1.4 Real floating and integer
1 When a finite value of real floating type is converted to an integer type other than _Bool,
the fractional part is discarded (i.e., the value is truncated toward zero). If the value of
the integral part cannot be represented by the integer type, the behavior is undefined.50)

2 When a value of integer type is converted to a real floating type, if the value being
converted can be represented exactly in the newtype, it is unchanged. If the value being
converted is in the range of values that can be represented but cannot be represented
exactly,the result is either the nearest higher or nearest lower representable value, chosen
in an implementation-defined manner.Ifthe value being converted is outside the range of
values that can be represented, the behavior is undefined.

50) The remaindering operation performed when a value of integer type is converted to unsigned type
need not be performed when a value of real floating type is converted to unsigned type. Thus, the
range of portable real floating values is (−1, Utype_MAX+1).




nicolas.sitbon

  • Guest
Re: float to int conversion
« Reply #2 on: June 24, 2009, 10:37:13 AM »
wikipedia can help too : http://en.wikipedia.org/wiki/Floating_point
Quote
round toward zero (sometimes called "chop" mode; it is similar to the common behavior of float-to-integer conversions, which convert −3.9 to −3)