Introduction to the Fundamentals of C++ Double

Predominantly, there are three major categories of data types in C++ - primary, derived, and user-defined data types. Primary data types in C++ (also known as primitive data types) are the data types that are provided by the language and are inbuilt. The C++ double data type falls under this category. This data type is widely used by programmers and is used to store floating-point numbers. All real numbers are floating-point values. A variable can be declared as double by adding the double keyword as a prefix to it. 

You majorly used this data type where the decimal digits are 14 or 15 digits. However, one must use it cautiously as it consumes memory storage of 8 bytes and is an expensive method. 

Syntax of Double in C++

The syntax to declare a variable of double type:

double variable_name;

double var_1, var_2, var_3;

It specifies the keyword double followed by the variable name to declare a variable of the double type. The following examples show different ways in which it can initialize a double variable:

// variables of double type

double var1 = 5.999999;

double var2 = 5.0;

double var3 = 5;

double var4 = -5.0000;

How Does Double Data Type work in C++?

  • The C++ double can hold floating-point values of up to 15 digits taking up a space of 8 bytes in the memory.
  • The range of the values that can be stored in a double type variable is 1.7E - 308 to 1.7E + 308.
  • The compiler in C++, by default, treats every value as a double and implicitly performs a type conversion between different data types.
  • Generally, the double type is used as it is more precise and prevents a loss of data in terms of significant digits.

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

Rules and Regulations for Using Double in C++

There are no hard and fast rules for using double in C++, nevertheless, some regular rules are there that make the code cleaner and help in understanding the double data type in a better way. 

  • The C++ double should have a floating-point precision of up to 15 digits as it contains a precision that is twice the precision of the float data type.
  • When you declare a variable as double, you should initialize it with a decimal value. For example, 3.0 is a decimal number. However, if you initialize it with 3, it will also work fine because although 3 and 3.0 seem to be identical i.e., an integer, there is a big difference in their internal representation.
  • When you perform the division or multiplication operation, both the numbers should be of the double data type or else there could be a loss of some data.
  • If you declare a variable as float and during initialization you did not add f in the end, it will consider it as a double variable. For example:

// it is considered as a float variable

float n = 1.414f;

//it is considered as a double variable

float n = 1.414;

Examples of C++ Double

The following examples illustrate the double data type in C++.

Example 1: Program to Find the Surface Area and Volume of a Sphere

#include <iostream>

using namespace std;

// function to calculate surface area and volume

// of a sphere

void sphere(int radius)

{

    // variables to hold double values

    double surfaceArea, sphereVolume;

    surfaceArea = 4 * 3.14 * radius * radius;

    sphereVolume = (surfaceArea * radius ) / 3; 

    cout << "The surface area of the sphere is: " << surfaceArea;

    cout << "\n\nThe volume of the sphere is: " << sphereVolume; 

}

int main()

{

    int radius = 6;

    sphere(radius);

    cout << "\n\n";

    return 0;

}

Cpp_Double_1. 

In the above example, the variables surfaceArea and sphereVolume of double type are declared to store the results calculated in the function sphere(). The function finds the surface area and volume of a sphere, which can be floating-point values.

Example 2: Program to Perform Arithmetic Operations on the Double Type Values

#include <iostream>

using namespace std;

double findSum(double x, double y)

{

    return x + y;

}

double findDifference(double x, double y)

{

    return x - y;

}

double findProduct(double x, double y)

{

    return x * y;

double findQuotient(double x, double y)

{

    return x / y;

}

int main()

{

    double value1 = 10.45, value2 = 6.28;    

    cout << "The sum is: " << findSum(value1, value2) << "\n\n";

    cout << "The difference is: " << findDifference(value1, value2) << "\n\n";

    cout << "The product is: " << findProduct(value1, value2) << "\n\n";

    cout << "The quotient is: " << findQuotient(value1, value2) << "\n\n"; 

    return 0;

}

Cpp_Double_2 

In the above example, the basic arithmetic operations, addition, subtraction, multiplication, and division are performed on two double operands value1 and  value2. The result of their division produces 1.664012738, but only 6 digits are printed because the cout only prints 6 digits by default by rounding off the value.

Example 3: Program to Find the Cube Root of a Number

#include <iostream>

using namespace std;

double findCube(double num)

{

    double ans;

    double precision = 0.000001;

    // calculate the integer part

    for (double ans = 1; (ans * ans * ans) <= num; ++ans)

        ;

    ans--;

    // Calculate the fractional part

    for (ans; (ans * ans * ans) < num; ans += precision)

        ;

    return ans;

int main()

{

    int num = 5;

    cout << "The cube root of the number is: ";

    cout << findCube(num) << "\n\n"; 

    return 0;

}

Cpp_Double_3 

In the above example, it calculates the cube root of an integer. It stores the result in a double variable ans. 

Difference Between Float and Double

In C++, float and double are both used to store floating-point numbers. Floating-points values are real numbers, for eg: 1801.0, -4.258, or 0.08244. These two data types differ from each other in many ways. Now, understand how the float differs from the  C++ double.

Float: The C++ float type is a primitive data type that holds floating values up to 7 digits. 

Double: The C++ double is also a primitive data type that is used to store floating-point values up to 15 digits.

The following program illustrates the difference between C++ float and C++ double:

#include<iostream>

using namespace std; 

int main()

{

    // initialize float and double variables

    float var1 = 1.1426f;       // the float value should end with an 'f'

    double var2 = 1.1426576; 

    // print the size of the float variable

    cout << "The float datatype takes " << sizeof(var1) << " bytes in the memory.";

    // print the value of the long double variable

    cout << "\n\nThe value stored in the variable is: " << var1;

    cout << "\n\n";

    // print the size of the long double variable

    cout << "The long double datatype takes " << sizeof(var2) << " bytes in the memory."; 

    // print the value of the long double variable

    cout << "\n\nThe value stored in the variable is: " << var2;

    cout << "\n\n";

    return 0;

}

Cpp_Double_4 

In the above example, variables of float and double types are initialized with floating-point values. The value of the float variable ends with an “f” suffix because the compiler by default treats all values as double. The sizeof() operator is used to print the size of float and double data types in bytes. 

The following comparison chart highlights the key difference between the C++ float and the C++ double:

FLOAT

DOUBLE

Float consumes 4 bytes of memory for storage.

Double consumes 8 bytes of memory for storage.

Float has comparatively less precision and is used to store decimal numbers with fewer digits.

Double has almost twice the precision as float and is used to store decimal numbers with more digits.

It has a 32-bit floating-point precision according to IEEE.

It has a 64-bit floating-point precision according to IEEE.

It stores up to 7 decimal points and rounds off the rest of the digits.

It can store up to 15 decimal points without rounding them off.

setprecision() to Specify Decimal Points

The setprecision() method in C++ is used to set the precision of floating points up to a certain number of significant digits. It provides a way to control the number of floating points. It is mainly useful in cases where the resulting number is irrational and repeating, i.e., where the decimal points repeat themselves after reaching a certain point. This function can be used in the program by adding the iomanip header file.

The Syntax for the setprecision() Method:

setprecision(int n)

Parameter

This function accepts an integer that specifies the number of significant digits up to which the precision has to be set.

Return Value

This function returns nothing. It is just a manipulator function that formats the floating-point values.

The following examples illustrate the working of setprecision() function in C++:

Example 1

#include <iostream>

#include <iomanip>

using namespace std;

int main()

{

    // initialising the value of pi

    // upto two places

    double pi = 3.142857142857;

    cout << "Value of pi before using setprecision(): "

         << pi << endl;

    // Using setprecision()

    cout << "Using the setprecision to set the precision upto 4: ";

    cout << setprecision(4);

    cout << pi << endl;

 // Using setprecision()

    cout << "Using the setprecision to set the precision upto 8: ";

    cout << setprecision(8);

    cout << pi << endl;

    // setting the precision value that

    // is beyond the number of digits

    // in the initialised value

    cout << "Using the setprecision to set the precision upto 15: ";

    cout << setprecision(15);

    cout << pi << endl;

    return 0;

}

Cpp_Double_5. 

In the above example, although the total number of digits after the decimal of the initialized value of pi is 13, the printed value contains only 6 decimal points, as in MinGW. The cout function prints the number up to 6 digits at max and truncates the rest of the decimal digits by rounding off the value. You used the setprecision() function up to 4 and 8 and got the expected output but when you tried to set the precision up to 15; it gave the maximum digits of the initialized value that is 13.

Example 2

#include <iostream>

#include <iomanip>

using namespace std;

int main()

{

    double pos = 1.41421356, neg = -1.41421356;

    //using setprecision()

    cout << "Setting precision to 0:\t";

    cout << setprecision(0) << "pos = " << pos << " ";

    cout << "neg = " << neg << endl;

    //using setprecision()

    cout << "Setting precision to 1:\t";

    cout << setprecision(1) << "pos = " << pos << " ";

    cout << "neg = " << neg << endl;

    //using setprecision()

    cout << "Setting precision to 2:\t";

    cout << setprecision(2) << "pos = " << pos << " ";

    cout << "neg = " << neg << endl;

 //using setprecision()

    cout << "Setting precision to 3:\t";

    cout << setprecision(3) << "pos = " << pos << " ";

    cout << "neg = " << neg << endl;

    //using setprecision()

    cout << "Setting precision to 4:\t";

    cout << setprecision(4) << "pos = " << pos << " ";

    cout << "neg = " << neg << endl;

}

Cpp_Double_6. 

In the above example, the setprecision() function is used to set the precision of values of √2 and -√2 to 0, 1, 2, 3, and 4.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Different Precisions For Different Variables

A double variable can store a floating-point value of precision of up to 15 digits.  You can format the value stored in a double variable to different precisions using various approaches such as using the setprecision() method or using the manipulators like fixed, scientific, hexfloat, and defaultfloat. The precision can be set by specifying the number of significant decimal digits. The following examples illustrate some of the most common approaches to format double variables to different precisions.

Example 1: Using the fixed Manipulator.

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

    // double variable to hold a floating-point value

    double value1 = 3.1415926535;

    // double variable to hold an exponential value

    double value2 = 124e+3;

  // print the values using 'fixed'

   cout << "The value stored in the first variable is: " << fixed << value1; 

    cout << "\n\n";

    cout << "The value stored in the second variable is: " << fixed << value2; 

    cout << "\n\n"; 

    return 0;

}

Cpp_Double_7 

In the above example, the fixed manipulator of the C++ standard library is used to set the number of significant digits to 5, by specifying the precision. The precision of a double type and an exponential value is set using the fixed manipulator.

Example 2: Using the scientific Manipulator.

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

    // double variable to hold a floating-point value

    double value1 = 3.1415926535;

    // double variable to hold an exponential value

    double value2 = 124e+3; 

    // Set the precision

    cout.precision(5);

    // print the values using 'scientific'

    cout << "The value stored in the first variable is: " << scientific << value1; 

    cout << "\n\n"; 

    cout << "The value stored in the second variable is: " << scientific << value2; 

    cout << "\n\n";

     return 0;

}

Cpp_Double_8. 

In the above example, the manipulator scientific of the standard library is used to print the values stored in the double variables. The statement cout.precision(5) sets the precision of the digits to 5. So, a double value of 3.1415926535 is printed in the scientific format with 5 digits after the decimal as 3.14159e+00.

Long Double in C++

The long double is another data type in C++ that is used to store floating-point numbers. It takes up the size of up to 12 bytes whereas the float and the double occupy 4 bytes and 8 bytes respectively. The values initialized with the data type long double must end with “L”. For example:

// declaring a long double variable

long double n = 1.414L;

The following example illustrates the long double in C++:

#include<iostream>

using namespace std;

int main()

{

    // initialize a variable of long double type

    long double var1 = 1.1426e+5;

    // print the size of the long double variable

    cout << "The long double takes " << sizeof(var1) << " bytes in the memory.";

    // print the value of the long double variable

    cout << "\n\nThe value stored in the variable is: " << var1;

    cout << "\n\n";

    return 0;

}

Cpp_Double_9 

In the above example, a long double variable (var1) is initialized. The sizeof() operator determines the size of the variable var1 in bytes. The output displays the size of the variable i.e. 12 bytes and its value i.e. 114260.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Final Thoughts!

To sum up, in this article you learned about one of the most popular and widely used primitive data types in C++ called the double data type. The double data type is used to store floating-point numbers and you can even define the precision using appropriate methods. You learned the syntax for creating a double data type and saw how the double data type works. 

Next, you learned a few rules and regulations that you must keep in mind while declaring double data types in C++. Moving ahead, you saw how and where you can use the double type with a few examples. You understood the fundamental difference between the double and float data types and used the set precision method to set the number of precision digits in a double value. In the end, you learned how to use another variation of double called long double to store even larger double data types.

If you want to learn more about such fundamental concepts in C++, you can check our complete guide on C++ for beginners.

If you want to pursue a career in Full Stack Web Development, you should check out Simplilearn’s 9-month training program on full-stack web development taught by industry experts. These experts will be available with you throughout your journey to solve your queries. You will learn skills and tools such as Java and its frameworks including spring, hibernate, JPA, etc., agile methodologies, DevOps, front-end tools such as CSS, HTML, JS, servlets, etc.

If you are interested in learning more about such technologies, check out our complete list of free online courses and try a few.

If you have any queries related to this article on “C++ double” or any other suggestions, please use the comment box to drop a comment and our experts will get back to you as soon as possible.

Happy Learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.