Jump to content

Typecasting and Truncation

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
Namesake

Namesake

    Newbie

  • Members
  • PipPip
  • 21 posts
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.:


	double bob = 4.123999;

	int b =int(bob);


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.

Are there any downsides to int typecasting of doubles/floating points ?:confused:

#2
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts
I suppose it depends on your desired output.
#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
*/
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.

Also, you are going to run into issues if the double value is outside of the range of a int.

#3
Namesake

Namesake

    Newbie

  • Members
  • PipPip
  • 21 posts
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 !

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
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).
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#5
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts
Aye.
#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
*/