Thursday, October 15, 2009

C++ number precision

Today I learned a very useful feature that C++ has.  It is the precision of numbers when using streams. Below I will show how the .precision function is important if you want precision when displaying numbers to the screen using the cout function or when writing numbers to a file using ofstream.  Undoubtedly there are other ways to use it, but I am more concerned with those two functions.

COUT
The below code will produce an output that is the full 10 digits in length

double digit = 5.000000001
cout.precision(10);
cout << digit << endl;
visit here for a more in depth explanation/example

OFSTREAM 

The below code will save your value in 10 digit format to a file (appending it to the end)
// Make a value to write to a file called file.txt
double value = 15.12345678;

// Create and open a stream
ofstream myFileWrite; 
myFileWrite.open("file.txt",ios::app); // append to the end of the file

// Make sure we opened it right
if (!myFileWrite.is_open())
   return -1;


// Define the precision to write at 
myFileWrite.precision(10);

// Write the value to the file at the end of the file 
myFileWrite << value << endl;

// Close the file
myFileWrite.close();

No comments:

Post a Comment