Set precision with fstream to output file - format double

21,164

Try using

#include <iomanip>  // std::setprecision()

f << std::fixed << setprecision(2) << endl;

std::setprecision() sets the number of significant digits, not the number of decimals places. For example

cout << setprecision(3) << 12.3456 << endl;

would output 12.3
Sending in fixed first makes it so you are setting the precision from a fixed position (the decimal place) rather than from the first digit of the floating point value.

Share:
21,164
Chisx
Author by

Chisx

I love programming. M.S. in Computer Science. iOS Developer. Languages: C C++ C# HTML/CSS Java Javascript JQuery Objective-C Python PHP SQL x86 Assembly (MASM) APIs/Frameworks/IDEs/OS: Adobe Illustrator &amp; Photoshop Eclipse IntelliJ Laravel Linux MSDOS MPI .NET Sequel Pro Unix Visual Studio (Professional/Ultimate), and VScode Xamarin Xcode 3DSMax Enjoys programming, music, mathematics, astronomy, astrophysics, investment, particle theory, foreign languages(currently Korean, Japanese, German), nice cars and houses, and all the finer things in life.

Updated on July 09, 2022

Comments

  • Chisx
    Chisx over 1 year

    I cannot find an answer for how I might use an already opened fstream to output formatted doubles to a text file. Currently my code is doing this:

    int writeToFile (fstream& f, product_record& p)
    {
       if (!f){
          cout << "out file failed!!error" << endl;
          return -1;
       } else {
    
          f << p.idnumber << endl;
          f << p.name << endl;
          f << p.price << endl;
          f << p.number << endl;
          f << p.tax << endl;
          f << p.sANDh << endl;
          f << p.total << endl;
          f << intArrToString( p.stations ) << endl;
    
       }
    }
    

    Where p is struct called product_record and price, tax, sANDh, and total are all doubles I have tried doing f << setprecision(4) << p.price << endl; but this does not work. How can i format this double to have a precision of two decimal places. Like this "#.00". How can I achieve this using specifically fstream?

    Also, fyi, the overall task is to simply read a txt file, store data in a struct, add structs to a vector and then read from the structs to print to an output file. The input file already has the doubles formatted like 10.00, 2.00 and such(2-decimal places)