Thread: Simple c++ question

  1. #1
    Registered User
    Join Date
    Mar 2002

    Simple c++ question

    I know how to do it with printf, but how do you limit the amount of digits when using cout with a float.

  2. #2
    Registered User quagsire's Avatar
    Join Date
    Jun 2002
    float floatvar = 1.234567;
    cout << setprecision(4) << floatvar; // will output "1.23"

  3. #3
    Seven years? civix's Avatar
    Join Date
    Jul 2002
    ...uh...what quagsire said...

  4. #4
    Registered User
    Join Date
    Apr 2002
    Actually, there is an addendum to quagsire's post here, at least, where Borland C++Builder 4 & 5 and MSVC++ are concerned.
    #include <iostream>
    #include <conio.h>
    #include <iomanip> // for setprecision and fixed  
    int main(){
    float floatvar = 10.23456789;
    std::cout << std::setprecision(4) << floatvar << std::endl;
    std::cout << std::fixed << std::setprecision(4) << floatvar << std::endl;
    std::cout << std::setprecision(4) << floatvar << std::endl;
    return 0;
    The listed code displays:


    Note that 'fixed' determines the number of places that follow the decimal point when used in conjuntion with 'setprecision()' and remains in effect until disabled.

    A handy thing to be aware of.

    P.S. Notice the rounding of the fraction as opposed to truncation.

    "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. Simple question regarding variables
    By Flakster in forum C++ Programming
    Replies: 10
    Last Post: 05-18-2005, 08:10 PM
  2. Simple class question
    By 99atlantic in forum C++ Programming
    Replies: 6
    Last Post: 04-20-2005, 11:41 PM
  3. Simple question about pausing program
    By Noid in forum C Programming
    Replies: 14
    Last Post: 04-02-2005, 09:46 AM
  4. simple question.
    By InvariantLoop in forum Windows Programming
    Replies: 4
    Last Post: 01-31-2005, 12:15 PM
  5. simple fgets question
    By theweirdo in forum C Programming
    Replies: 7
    Last Post: 01-27-2002, 06:58 PM