1 minute read

Introduction

In this tutorial, you will learn how to convert a float to an int in the C++ programming language. There are a few ways to achieve this, and we will be covering the main methods:

Method #1: Using static_cast

We can use the static_cast method to convert a float to an int, as shown below:

#include <iostream>

int main(){
    float x = 3.14f;
    int y = static_cast<int>(x);
    std::cout << y << std::endl; //Prints out 3
    return 0;
}

It is important to note that this method simply truncates the decimal values and converts the float to an int.

Method #2: Using C-style casting

We can also use C-style casting to convert a float to an int.

#include <iostream>

int main(){
    float x = 3.14f;
    int y = (int) x;
    std::cout << y << std::endl; //Prints out 3
    return 0;
}

This method also truncates the decimal values and converts the float to an int.

Conclusion

In this tutorial, you have learned how to convert a float to an int in C++ using the static_cast method and the C-style casting method. Both methods will truncate the decimal values of the float, resulting in an int. It’s important to keep in mind that this will truncate any decimal values, not round them.