Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to securely convert this double into an int?

Tags:

c

objective-c

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).

like image 984
Proud Member Avatar asked Feb 02 '11 18:02

Proud Member


People also ask

How do you convert a double to an int in C++?

The syntax for typecasting is like the syntax for a function call. For example: double pi = 3.14159; int x = int (pi); The int function returns an integer, so x gets the value 3.

What happens when you turn a double into an int?

As we know double value can contain decimal digits (digits after decimal point), so when we convert double value with decimal digits to int value, the decimal digits are truncated.


2 Answers

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)
like image 171
Varun Madiath Avatar answered Oct 26 '22 23:10

Varun Madiath


int converted = (int)round(theDouble);
like image 30
Noah Witherspoon Avatar answered Oct 26 '22 23:10

Noah Witherspoon