1. Technology

C++ Handling Ints and Floats


3 of 8

Precision Arithmetic

Double Trouble

There's no long float, but there is a double type that is twice as big as float.
  • Float: Occupies 4 bytes. Range 17x10-38 to 1.7x1038
  • Double: Occupies 8 bytes. Range 3.4x10-308 to 3.4308
Unless you're doing scientific programming with very large or small numbers, you'll only use doubles for greater precision. Floats are good for 6 digits of accuracy but doubles offer 15.


Consider the number 567.8976523. It is a valid float value. But if we print it out with this code below you can see lack of precision appearing. The number has 10 digits but is being stored in a float variable with only six digits of precision.

 #include <iostream>
 using namespace std;
 int main(int argc, char* argv[])
 float value = 567.8976523;
 cout.precision(8) ;
 cout << value << endl;
 return 0;

See About Input and Output for details on how cout works, and how to use precision. This example sets the output precision to 8 digits. Unfortunately floats can only hold 6 and some compilers will issue a warning about converting a double to a float. When run, this prints out 567.89764

If you change the precision to 15, it prints as 567.897644042969. Quite a difference! Now move the decimal point two to the left so the value is 5.678976523 and rerun the program. This time it outputs 5.67897653579712. This is more accurate but still different.

If you change the type of value to double and the precision to 10 it will print the value exactly as defined. As a general rule, floats are handy for small, non integer numbers but with more than 6 digits, you have to use doubles.

On the next page : Learn about Computer Arithmetic.

  1. About.com
  2. Technology
  3. C / C++ / C#
  4. C++ Programming
  5. Learn C++ Programming
  6. C++ Handling Ints and Floats - Precision in Floats

©2014 About.com. All rights reserved.