CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2009
    Posts
    68

    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!!

  2. #2
    Join Date
    Feb 2002
    Posts
    4,640

    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

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: ifstream / ofstream precision

    Quote Originally Posted by karnavor View Post
    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
  •  





Click Here to Expand Forum to Full Width

Featured