# [vtkusers] Re: Float to Int

David Gobbi dgobbi at atamai.com
Wed Jul 19 08:38:17 EDT 2006

```Russell Hind wrote:
> Patrícia Gonçalves wrote:
>> I'm not familiar with Tcl and I don't know if it has a Round method,
>> but you can make one yourself:
>>
>>     float j = (number);
>>     int i = j;        // making i equal to the floor of (number)
>>     if (j-i>=0.5) i=i+1;
>>
>
> Why not just
>
> float j = (number);
> int i = (j + 0.5f);
>
The problem with this is that the addition introduces some
roundoff error.  For example, if j = 5.499999 and you add
0.5, you might get 6.0 due to roundoff, instead of
5.999999 as you would expect.  The method that Patricia
gave does not suffer from roundoff error.

Both of these methods only work on on positive numbers,
since a float-to-int conversion is a truncation operation
rather than a floor operation.

The way to do exact rounding in C++ is the following:

double x = value;
double y = floor(x);
if (x - y >= 0.5) { y++; }
int i = y;

You don't want to convert to int until the very end, or else
overflow will not be handled properly.

- David

```