# Casting double to int, when it is reasonable safe?

This topic is 3719 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'd like trying implement a simple game using C. One of the first problems I have to solve is how to rotate points in a plane. The linear algebra gives all answers, but computers do not understand real numbers. So I am using doubles. The double (at least in my machine) has twice as bit of a int. But it also tries to emulate a much larger set... And so I was wondering, it when it is safe cast a double in a int? It is in the reasonable magnitude of numbers that are the screen coordinates? Thanks everyone.

##### Share on other sites
It should always be safe to cast to an int in the sense that it won't horribly crash or throw exceptions or anything like that. Casting a double that's too large or too small to fit an int will probably just produce INT_MAX or INT_MIN (2^31-1 and -2^31 on 32-bit systems). If the double is between those, it will be rounded to either of the nearest ints (depending on the rounding mode, usually the one closer to zero).

Also, floating points don't 'emulate' anything. They are much like the scientific notation 123.4E56 with a certain precision for the mantissa and a range for the exponent.

##### Share on other sites
Quote:
 Original post by gdbetbAnd so I was wondering, it when it is safe cast a double in a int?It is in the reasonable magnitude of numbers that are the screen coordinates?
Assuming by "int" you mean a 32-bit signed integer, you have a range of about +/- 2 billion, with no fractional component.
So, so long as your double is in the range +/- 2 billion, and you don't mind losing the fractional component, it's safe. Although you'll normally want to do an explicit cast to prevent compiler warnings.

1. 1
2. 2
3. 3
Rutin
21
4. 4
5. 5
gaxio
10

• 14
• 30
• 13
• 11
• 11
• ### Forum Statistics

• Total Topics
631778
• Total Posts
3002310
×