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).
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.
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.
You're probably looking for the lround(double function). The signature looks like this.
long int lround(double).
Other options are
int converted = (int)round(theDouble);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With