Thread: Setting precision?

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    38

    Setting precision?

    How can I set the number of decimal places when writing to an ofstream? I want to always write 2 decimal places, even if they are both zero.
    Thanks

  2. #2
    Registered User
    Join Date
    Nov 2005
    Posts
    38
    In C I have done something like the following:

    Code:
    fprintf(parout, "-weight=%2.f", weight);
    This will print out weight with 2 decimal places, even if they are both zero. Is there a way to do this in C++?
    Thanks

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    85
    use setprecision(2) with cout and include <iomanip>
    eg

    int x = 2.143234234;
    cout << setprecision(2) << x << endl;

  4. #4
    Registered User
    Join Date
    Nov 2005
    Posts
    38

    Doesnt seem to work!

    The setprecision function only seems to work if the positions are non zero. Is there some other way? Say I have weight = 10, and I want it to be printed as 10.00. Is there a way to do this?
    Thanks

    The set precision function takes a value n, and this is the maximum number of decimal places, but it doesnt necessarily use them all.
    Last edited by markucd; 01-23-2006 at 05:17 AM.

  5. #5
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
    double x = 2.143234234;
    cout << fixed  << setprecision(2) << x << endl;
    Kurt

  6. #6
    Registered User
    Join Date
    Nov 2005
    Posts
    38

    Thanks!

    That works

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Setting Precision Confusion
    By dnguyen1022 in forum C++ Programming
    Replies: 11
    Last Post: 01-14-2009, 10:38 AM
  2. Format Precision & Scale
    By mattnewtoc in forum C Programming
    Replies: 1
    Last Post: 09-16-2008, 10:34 AM
  3. Setting decimal precision in fstream
    By CodeMonkey in forum C++ Programming
    Replies: 1
    Last Post: 04-01-2003, 06:08 PM
  4. Your favourite fantasy game setting?
    By fry in forum Game Programming
    Replies: 4
    Last Post: 10-16-2002, 06:26 AM
  5. setting a float to 4 digit decimal precision
    By river-wind in forum C Programming
    Replies: 8
    Last Post: 01-21-2002, 05:03 PM