What are the different techniques for a floating point type to an integer type conversion, in c++?
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.
I believe you can do this using a cast:
float f_val = 3.6f;
int i_val = (int) f_val;
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.
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
Check out the boost NumericConversion library. It will allow to explicitly control how you want to deal with issues like overflow handling and truncation.