# floating point to int problem?

**URL:** <https://forums.digi.com/t/floating-point-to-int-problem/10465>\
**Category:** Rabbit\
**Created:** [April 19, 2010, 8:10pm UTC](https://forums.digi.com/t/floating-point-to-int-problem/10465 "2010-04-19T20:10:13Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![tash\_neo](https://avatars.discourse-cdn.com/v4/letter/t/a3d4f5/32.png) [@tash\_neo](https://forums.digi.com/u/tash_neo)\
**Post date:** [April 19, 2010, 8:10pm UTC](https://forums.digi.com/t/floating-point-to-int-problem/10465/1 "2010-04-19T20:10:13Z")

</div>

I have a floating point number that has been input by a user.

I need to multiply it by 10 and use it as an index into a lookup table.

```auto
float fnum;
int inum;

fnum = 65.7;

fnum *=10; //shows float 657 in the debugger

inum = (int)fnum; // inum = 656??

```

Any way to make this work reliably?

---

<div class="post-metadata">

**Author:** ![jimmcguffin](https://avatars.discourse-cdn.com/v4/letter/j/5daacb/32.png) [@jimmcguffin](https://forums.digi.com/u/jimmcguffin)\
**Post date:** [April 23, 2010, 12:25am UTC](https://forums.digi.com/t/floating-point-to-int-problem/10465/2 "2010-04-23T00:25:30Z")

</div>

Have you tried this:

fnum \*=10; //shows float 657 in the debugger  
inum = (int)(fnum + 0.5); // rounds off

---

<div class="post-metadata">

**Author:** ![thomas.kuhlmann](https://sea2.discourse-cdn.com/flex016/user_avatar/forums.digi.com/thomas.kuhlmann/32/7_2.png) [@thomas.kuhlmann](https://forums.digi.com/u/thomas.kuhlmann)\
**Post date:** [June 16, 2010, 8:46am UTC](https://forums.digi.com/t/floating-point-to-int-problem/10465/3 "2010-06-16T08:46:36Z")

</div>

Note that not all integer values can be exactly expressed in double.  
So even when your debugger shows 657, this was maybe internally 656.99996.

You can use library function round() to make it work:

[http://www.gnu.org/s/libc/manual/html\_node/Rounding-Functions.html](http://www.gnu.org/s/libc/manual/html_node/Rounding-Functions.html)

This is also a reason why you should never compare doubles for beeing equal:

if ( ((double)a) == ((double)b) )

as two doubles will not match most of the time. To compare if they are “nearly equal” you should alway do:

if ( abs( a - b) \< EPSILON )

where you define EPSILON = 10 e-6 or whatever is exact enough for your application.
