How to Convert Float to Int in C++

  1. Use Direct Assignment to Convert Float to Int
  2. Use C-style Cast to Convert Float to Int
  3. Use static_cast to Convert Float to Int

This article will demonstrate multiple methods about how to convert a float to an int in C++.

Use Direct Assignment to Convert Float to Int

The conversion between the float and int values can be done using the assignment operator. In this case, the float variable will be implicitly converted to the int type, and the value will be narrowed down to the second type, losing all digits after the decimal point. Note that we use a vector of int to store the float and then output each integer to console for better demonstration.

#include <iostream>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

int main(){
    vector<float> f_vec { 12.123, 32.23, 534.333333339 };
    vector<int> i_vec;

    i_vec.reserve(f_vec.size());
    for (const auto &f : f_vec) {
        i_vec.push_back(f);
    }

    for (const auto &i : i_vec) {
        cout << i << "; ";
    }
    cout << endl;

    return EXIT_SUCCESS;
}

Output:

12; 32; 534;

Use C-style Cast to Convert Float to Int

Another solution is a C-style cast with (typename) notation. This method is usually considered unsafe in modern C++, but if the programmer uses it correctly, the code will run as expected. Note to never cast pointers to incomplete classes as it can lead to undefined behavior.

#include <iostream>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

int main(){
    vector<float> f_vec { 12.123, 32.23, 534.333333339 };
    vector<int> i_vec;

    i_vec.reserve(f_vec.size());
    for (const auto &f : f_vec) {
        i_vec.push_back(int(f));
    }

    for (const auto &i : i_vec) {
        cout << i << "; ";
    }
    cout << endl;

    return EXIT_SUCCESS;
}

Output:

12; 32; 534;

Use static_cast to Convert Float to Int

As per the modern C++ recommendation, one should utilize named cast to convert a float value to an integer. static_cast converts the types without checking the value; hence the programmer is responsible for ensuring correctness. Note that named casts and their behavior is quite complicated to grasp with a single overview, so here’s the full manual of static_cast listing all the edge cases and features.

#include <iostream>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

int main(){
    vector<float> f_vec { 12.123, 32.23, 534.333333339 };
    vector<int> i_vec;

    i_vec.reserve(f_vec.size());
    for (const auto &f : f_vec) {
        i_vec.push_back(static_cast<int>(f));
    }

    for (const auto &i : i_vec) {
        cout << i << "; ";
    }
    cout << endl;

    return EXIT_SUCCESS;
}

Output:

12; 32; 534;

Related Article - C++ Float

  • How to Convert Float to String in C++
  • How to Generate a Random Float Number in C++