Section 2 - Floating Point Types

2B.2.1 Float and Double Types

Next, we visit the floating point data types, float and double.  These are each capable of holding numbers that include decimals and fractional parts.  float constants, or literals, are distinguished by writing the letter F or f after the constant, as in:

3.14159f

or

5.7e+9F

double constants have no letters after them.  So if you type a number like 123.456 you are implying that it is a double not a float.

double gives considerably more precision. If you need 8 or 9 decimal places of accuracy, float will do:

100.3032f
1.23232e-14f

but for 10 or more decimal places I use double:

100.3032321100194
-.0000000000001
2.123123408456345e-5

Remember, constants with a decimal point but without any special character after them are assumed to be double. With an "f" following them, they are assumed to be float:

double s;
s = 1.23; /* even if you don't use the precision
it's there */
float r;
r = 5.4f;

You should probably always use doubles -- they are easier to write and more powerful. If you see me talk about or use a float in this class, you can usually just replace it with a double.

scenic post office sign

C++ takes care of displaying each object using the proper notation without messy formatting required by us programmers:

float  f;
double   l;

f = 31.23232e-14f;
l = 123456789123.456789;

cout << "The numbers are  " << f << " " << l << endl;

results in:

The numbers are 3.12323e-013 1.23457e+011

Note that I placed " " (a string literal consisting of just one space) between the numbers. That makes it possible to see them without confusion. If, instead, we had tried this without the space like so:

cout << "The numbers are  " << f << l << endl;

our output would have been:

The numbers are  3.12323e-0131.23457e+011