开发者

How to securely convert this double into an int?

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 do开发者_运维问答uble? 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).


You're probably looking for the lround(double function). The signature looks like this.

long int lround(double).

Other options are

  • long int lrint(double)
  • long long int llrint(double)
  • long long int llround(double)


int converted = (int)round(theDouble);


Do this:

int converted = (int)(round(theDouble));


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜