Thread: numbers with decimals

  1. #1
    Registered User
    Join Date
    Jan 2002

    Question numbers with decimals

    im using the double command for an array that has decimals in it, but when it prints out at the end there is too many numbers after the decimal.

    so i was wanting to know if there is a way to make it so it only prints out up to 2 decimal places.

    Hooked On Phonics Didn't Work For Me!

  2. #2
    Registered User
    Join Date
    Oct 2001
    Try this.
       #include <iostream>
       #include <iomanip>
       using namespace std;
       double num = 40.3527;
       cout << "num:" << setprecision(2) << num << endl;

  3. #3
    Puchuk Puchuk
    how do you restrict the thing to calculate and round it to two decimal places ?

  4. #4
    Registered User
    Join Date
    Apr 2002
    how do you restrict the thing to calculate and round it to two decimal places ?
    You need to use the 'fixed' manipulator in conjunction with setprecision(). Without it, the setprecision() argument will determine the number of significant places that are displayed, not the number of decimal places.
    #include <iomanip> // for 'fixed'
    #include <cstdlib> // system call
    #include <iostream>
    using namespace std;
    int main(void)
    const double num = 123.45678;
    cout << "'fixed' flag not set:  " << setprecision(4) << num << endl;
    cout << "'fixed' flag set:      " << fixed << setprecision(4) << num << endl;
    double num2 = num * 10;
    cout.unsetf(ios::fixed);    // unsets the 'fixed' flag
    cout << "'fixed' flag not set:  " << setprecision(2) << num2 << endl;
    cout << "'fixed' flag set:      " << fixed << setprecision(2) << num2 << endl << endl;
    return 0;
    If you run this code, you'll see a rather significant difference when 'num2' is calculated and displayed.

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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Comparing numbers to a list of numbers held in a text file
    By jmajeremy in forum C++ Programming
    Replies: 3
    Last Post: 11-06-2006, 07:56 AM
  2. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 06:20 AM
  3. Replies: 4
    Last Post: 03-03-2003, 03:52 PM
  4. the definition of a mathematical "average" or "mean"
    By DavidP in forum A Brief History of
    Replies: 7
    Last Post: 12-03-2002, 11:15 AM
  5. A (complex) question on numbers
    By Unregistered in forum C++ Programming
    Replies: 8
    Last Post: 02-03-2002, 06:38 PM
Website Security Test