I have been researching on how to truncate a given (double/floating point) number, and it seems the easiest way to do so is through type casting, i.e.:
Although, it seems that a lot of sources on the net use rounding, the use of floors and ceiling to truncate these numbers. Type casting seems to be far easier than all of this.Code:double bob = 4.123999; int b =int(bob);
Are there any downsides to int typecasting of doubles/floating points ?![]()
I suppose it depends on your desired output.
If you felt that one of the results should have been 5 or -5, then truncation is not what you want. Thus the other options.Code:#include <iostream> void foo(double value) { int trunc = int(value); std::cout << "value = " << value << ", trunc = " << trunc << "\n"; } int main(void) { foo(4.123999); foo(4.823999); foo(-4.123999); foo(-4.823999); return 0; } /* my output value = 4.124, trunc = 4 value = 4.824, trunc = 4 value = -4.124, trunc = -4 value = -4.824, trunc = -4 */
Also, you are going to run into issues if the double value is outside of the range of a int.
This is exactly what I wanted
Could you expand what you mean by:
Also, you are going to run into issues if the double value is outside of the range of a int.
Thanks !
An int has a maximum value (such as 65,545) that it can store. This is MUCH less than a typical maximum value for a float (such as 9.3e20).
Aye.
Code:#include <stdio.h> int main() { double d = 1234.56789e+15; int i = d; printf("d = %g, i = %d\n", d, i); return 0; } /* my output d = 1.23457e+018, i = -2147483648 */
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks