1 minute read

Introduction

In this tutorial, you will learn how to convert a float to a double in the C++ programming language. There are many ways of achieving this, below we will highlight the main methods:

Method #1: Using static_cast

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

#include <iostream>

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

It is important to note that this method simply changes the type of the variable, it does not round or truncate the value.

Method #2: Using C-style casting

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

#include <iostream>

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

This method also changes the type of the variable, it does not round or truncate the value.

Conclusion

In this tutorial, you have learned how to convert a float to a double in C++ using the static_cast method or C-style casting. It is important to remember that these methods do not affect the value of the variable, they only change the type of the variable.