|
-
December 3rd, 2010, 04:20 PM
#1
ifstream / ofstream precision
Hello,
I'd like to ask two different questions on a related topic please...
1. When I am writing float data to a text file, I want to set the precision. I know that with std::cout, you can write "std::cout.precision(5)" to set the precision to 5 decimal places. But writing "std: fstream.precision(5)" does not work. How can I do this?
2. When I read the file back again, I want to add a load of zeros to each float, after the 5 decimal places. For example, if my data file has the value "1.23456", which has been limited by setting the ofstream precision to 5 decimal places, I want to read in this value again, such that the float variable becomes "1.234560000000.....". When I have tried just reading it in normally using std::ifstream, it in fact sets my flat variable to the value "1.234599999999999....". This may seem a trivial difference, but it is actually crucial for my program.
Thanks for any help!!
-
December 3rd, 2010, 04:35 PM
#2
Re: ifstream / ofstream precision
Floats and doubles are imprecise due to the way that the value is stored in memory. The computer cannot store 1.23456 exactly, which is why you see '1.2345999999999'.
Viggy
-
December 3rd, 2010, 04:37 PM
#3
Re: ifstream / ofstream precision
 Originally Posted by karnavor
1. When I am writing float data to a text file, I want to set the precision. I know that with std::cout, you can write "std::cout.precision(5)" to set the precision to 5 decimal places. But writing "std:  fstream.precision(5)" does not work. How can I do this?
You should be calling precision() on the ostream object that you're trying to write to; it's not a static method, so you can't call it on the ostream class itself.
Also, precision() only sets the number of decimal places if you've set the mode to std::fixed. In the default mode, precision() instead specifies the number of significant digits.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|