How to Convert Float to int in C++?

In C++, the float is a short term for floating point value that is used to define numeric values with decimal points. The floating point numbers can be converted to integers using the process called type casting. In this article, we will learn how to convert a float value to an int in C++.

Example:

Input:
float val1 = 3.14;
float val2 = 9.99;

Output:
Integer for float value 3.14 is: 3
Integer for float value 9.99 is: 10

Converting From Float to int in C++

To convert a floating value to an int value, first use the std::round() function that rounds the float to the nearest whole number, and then we can use the static_cast operator to cast the result to an integer.

Syntax to Convert Float to int in C++ 

int intValueName = static_cast<int>(round(floatValueName)); 

C++ Program to Convert Float to int

The below program demonstrates how we can convert a floating value to an integer in C++.

C++
// C++ program to convert float to int using std::round and
// casting
#include <cmath> 
#include <iostream>
using namespace std;

int main()
{
    // Define float values
    float floatValue1 = 3.14;
    float floatValue2 = 9.99;

    // Use std::round and static_cast to convert the float
    // values to int type
    int intValue1
        = static_cast<int>(round(floatValue1));
    cout << "The integer for float value " << floatValue1
         << " is " << intValue1 << endl;

    int intValue2
        = static_cast<int>(round(floatValue2));
    cout << "The integer for float value " << floatValue2
         << " is " << intValue2 << endl;

    return 0;
}

Output
The integer for float value 3.14 is 3
The integer for float value 9.99 is 10

Time Complexity: O(1)
Auxiliary Space: O(1)