OneBite.Dev - Coding blog in a bite size

Convert Variable From Int To Float In C++

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

In the realm of C++ programming, changing a variable from an integer to a float can be quite handy. This article will provide a succinct explanation on how to convert int to float in C++.

Code snippet to convert int to float in C++

#include<iostream>
using namespace std;
int main() 
{
    int num1 = 10;
    float num2;

    num2 = static_cast<float>(num1);

    cout<<"After conversion, the value of num2 : "<< num2;
    return 0;
}

This is a simple piece of C++ code that changes an integer to a float.

Code Explanation for converting int to float in C++

In this code example, we first import the standard I/O library. We then use the main() function which is the entry point of every C++ program.

#include<iostream>
using namespace std;
int main() 
{

Next, we declare an integer variable num1 and a float variable num2. The num1 is initialized to 10 while num2 is not assigned any value yet.

    int num1 = 10;
    float num2;

The core of this conversion lies in the next line where we apply a static_cast<float>(num1). This is known as type casting in C++. Here, the type casting function changes the integer num1 to a float type and assigns it to num2.

    num2 = static_cast<float>(num1);

Finally, we print the value of num2 which should now be 10.0 instead of 10.

    cout<<"After conversion, the value of num2 : "<< num2;
    return 0;
}

That’s it! You have now successfully converted an integer to a float in C++.

c-plus-plus