How to safely convert this double to int?

I have a double, which is the time interval in seconds. Allowed values: 0.0, 0.5, 1.0, 1.5, etc.

Now I need to convert this value to int. But I can not do this:

int converted = (int)theDouble;

Because it may happen that my double due to floating point errors is 0.999999999, not 1.000000000. It would just cut off the tail, and we would end with 0 instead of 1. Also, when my double is 0.9, I want int to be 1. When it is 1.1, I want int to be 1. When it is 1, 8, I want int to be 2.

There is a round () function there, but Xcode does not show the documentation for this. The header reports that it returns double. So not what I need.

What is the safest way to get a close inner view of this double? Although this is double, I will never need a higher accuracy than 0.5 or a single fragmentary figure (I am not a mathematical genius and I do not know the exact scientific terms).

+5
source share
5 answers

Like others, you can round theDouble, but keep in mind that you should not rely on floating point variables for accurate accuracy. Instead of comparing theDoublewith an integer for equality, you should do something like this:

if (abs(theDouble - theInteger) <= 0.000001)
    doSomething();

Remember that before matching, before comparing, it will be passed to double, so it may not be exact.

Last thing causing:

int converted = (int) round(theDouble)

, , , . , 0, 0.5, 1.0, 1.5,..., - ?:

int converted = (int) (round(theDouble) + 0.1)
+2

, ( ). .

long int lround (double).

  • long int lrint (double)
  • long long int llrint (double)
  • long long int llround (double)
+7
int converted = (int)round(theDouble);
+5

:

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

round math.h. , int. lround ( math.h), int.

+2

All Articles