OneBite.Dev - Coding blog in a bite size

Convert Variable From Float To Int In C++

Code snippet for how to Convert Variable From Float To Int In C++ with sample and detail explanation

C++ is a general-purpose programming language that supports various data types such as int, float, double, boolean, char, etc. This article focuses on converting a variable from the float type to an integer type in C++.

Code snippet for Float to Integer Conversion

The following code demonstrates how you can convert a float into an int in C++:

#include<iostream>
using namespace std; 

int main() { 
    float myFloatNum = 9.99; 
    int myIntNum = (int) myFloatNum; 

    cout<<"The integer value is: "<< myIntNum; 
    return 0; 
}

The output of this program will be:

The integer value is: 9

Code Explanation for Float to Integer Conversion

In this tutorial on converting float to integer in C++, we will explore the code snippet step by step.

Line 1: #include<iostream>

This is the preprocessor directive used to include the “iostream” library in our program. This library is responsible for handling input/output operations.

Line 2: using namespace std;

This line tells the compiler to use the standard namespace which includes C++ objects like cout and cin.

Line 3-7:

int main() { 
    float myFloatNum = 9.99; 
    int myIntNum = (int) myFloatNum; 

    cout<<"The integer value is: "<< myIntNum; 
    return 0; 
}

This is where our main program starts. First, we declare a float variable myFloatNum and assign it the value 9.99. Then we declare an integer variable myIntNum.

In the next line, int myIntNum = (int) myFloatNum;, we convert the float variable to an integer. We use the type casting approach where (int) explicitly converts the float number into integer value. Please note that it also truncates the decimal part of the float value, it means any number after the decimal will be removed.

The next line cout<<"The integer value is: "<< myIntNum; prints the value of myIntNum to the console.

Finally, return 0; ends the program. This line denotes that the program has run without any error.

And there you have it. Using this simple method, you can convert a variable from float to int in C++.

c-plus-plus