Reputation: 40496
I have an double which is a time interval in seconds. Valid values are 0.0, 0.5, 1.0, 1.5, etc.
Now I need to convert this value into an int. But I cannot do this:
int converted = (int)theDouble;
Because what may happen is, that my double due to floating point errors is 0.999999999 rather than 1.000000000. It would just cut off the tail, and we'd end up with 0 instead of 1. Also, when my double is 0.9, I want an int that is 1. When it is 1.1, I want the int to be 1. When it is 1.8, I want the int to be 2.
There's a round() function but Xcode doesn't show a documentation for this. The header only tells it returns a double. So not what I need.
What's the safest way to get a close int representation of that double? Although it is a double I'll never need higher precision than 0.5 or one fragmental digit (I'm no math genius and don't know the exact scientific terms).
Upvotes: 5
Views: 4987
Reputation: 10244
As others have suggested, you can round theDouble
, but keep in mind you should never count on floating point variables for precise precision. Instead of trying to compare theDouble
with an integer for equality, you should do something like this:
if (abs(theDouble - theInteger) <= 0.000001)
doSomething();
Remember, theInteger is going to be cast to a double before the comparison, so it might not be precise either.
One last thing, calling:
int converted = (int) round(theDouble)
is slightly dangerous, because, as you said, the floating point error might bring the value down. If you know your value will only be 0, 0.5, 1.0, 1.5, ..., why not do something like this?:
int converted = (int) (round(theDouble) + 0.1)
Upvotes: 2
Reputation: 3252
You're probably looking for the lround(double function). The signature looks like this.
long int lround(double).
Other options are
Upvotes: 7
Reputation: 410662
Use round
in math.h
. It returns a double, but in your case you can cast it to an int. Or use lround
(also in math.h
), which takes a double and returns a long int.
Upvotes: 2