views:

203

answers:

7

What are the different techniques for a floating point type to an integer type conversion, in c++?

+5  A: 

Normal way is to:

float f = 3.4;
int n = static_cast<int>(f);
Naveen
A: 

I belive you want type casting

float var_a = 9.99;
int   var_b = (int)var_a;

if you had only tried to write

int var_b = var_a;

You would have got a warning that you can't implicitly (automatically) convert a float to an int, as you lose the decimal.

typecasting (putting the type you KNOW you want in brackets) tells the compiler you know what you are doing and are cool with it.

thecoshman
I don't get the down vote? care to give a reason?
thecoshman
Exact reason can give you who down vote you but I think you get down vote because it is in c not in c++
Muhammad Kashif Nadeem
@thecoshman, I didn't downvote, but it may be due to you using C style casts in C++ code. It's frowned upon as it's bad style
Glen
I am? really? sorry, that was the way I though I was meant to do them
thecoshman
A: 

I believe you can do this using a cast:

float f_val = 3.6f;
int i_val = (int) f_val;
Seidr
A: 

the easiest technique is to just assign float to int, for example:

int i;
float f;
f = 34.0098;
i = f;

this will truncate everything behind floating point or you can round your float number before.

sanjuro
A: 

http://www.codeproject.com/KB/cpp/static_cast.aspx

Muhammad Kashif Nadeem
A: 

Size of some float types may exceed the size of int. This example shows a safe conversion of any float type to int using the int safeFloatToInt(const FloatType &num); function:

#include <iostream>
#include <limits>
using namespace std;

template <class FloatType>
int safeFloatToInt(const FloatType &num){
   //check if float fits into integer
   if ( numeric_limits<int>::digits < numeric_limits<FloatType>::digits)
      // check if float is smaller than max int
      if( (num < static_cast<FloatType>( numeric_limits<int>::max())) &&
             (num > static_cast<FloatType>( numeric_limits<int>::min())) )
         return static_cast<int>(num); //safe to cast
   else{
      cerr << "Unsafe conversion of value:" << num << endl;
      //NaN is not defined for int return the largest int value
      return numeric_limits<int>::max();
      }
   else
      //It is safe to cast
      return static_cast<int>(num);

}
int main(){
   double a=2251799813685240.0;
   float b=43.0;
   double c=23333.0;
   //unsafe cast
   cout << safeFloatToInt(a) << endl;
   cout << safeFloatToInt(b) << endl;
   cout << safeFloatToInt(c) << endl;
   return 0;
}

Result:

Unsafe conversion of value:2.2518e+15
2147483647
43
23333
zoli2k
+1  A: 

Check out the boost NumericConversion library. It will allow to explicitly control how you want to deal with issues like overflow handling and truncation.

simong