Thread: How to set decimal precision...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    244

    How to set decimal precision...

    Is there an _easy_ way (i.e. a C++ function or operator) to set the precision to the right of the decimal in a floating point number? i.e. precision of 2 would display 23.5124 as 23.51

    Or would I need to write this up myself?

    Thanks

  2. #2
    CS Author and Instructor
    Join Date
    Sep 2002
    Posts
    511
    How about setprecision()

    Code:
    #include <iomanip>
    
    
    cout << fixed << setprecision(2) << value << endl;
    Mr. C: Author and Instructor

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    244
    setprecision sets the total number of digits to be displayed, not the number of digits after the decimal. WIth older compilers it used to work like that, but no more. Stupid, eh?

  4. #4
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    Quick follow-up to Mr. C's post, make certain to include the 'fixed' manipulator as he has. The standard display precision is six places - as I recall - but includes the value's mantissa in the count. That is, 123.45678 displays as 123.457 (note the rounding of the value).

    By using 'fixed', the argument supplied with setprecison() determines the number of places following the decimal.

    -Skipper
    "When the only tool you own is a hammer, every problem begins to resemble a nail." Abraham Maslow

  5. #5
    Registered User
    Join Date
    Aug 2001
    Posts
    244
    Ahhh cool, thanks.

  6. #6
    Redundantly Redundant RoD's Avatar
    Join Date
    Sep 2002
    Location
    Missouri
    Posts
    6,331
    cout<<setiosflags(ios::fixed | ios::showpoint | ios::right)<<setprecision(2);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Format Precision & Scale
    By mattnewtoc in forum C Programming
    Replies: 1
    Last Post: 09-16-2008, 10:34 AM
  2. Need some help...
    By darkconvoy in forum C Programming
    Replies: 32
    Last Post: 04-29-2008, 03:33 PM
  3. C help for network animator
    By fastshadow in forum Tech Board
    Replies: 7
    Last Post: 03-17-2006, 03:44 AM