I know how to do it with printf, but how do you limit the amount of digits when using cout with a float.
I know how to do it with printf, but how do you limit the amount of digits when using cout with a float.
float floatvar = 1.234567;
cout << setprecision(4) << floatvar; // will output "1.23"
Actually, there is an addendum to quagsire's post here, at least, where Borland C++Builder 4 & 5 and MSVC++ are concerned.
The listed code displays:Code:#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; getch(); return 0; }
10.23
10.2346
10.2346
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.
-Skipper
"When the only tool you own is a hammer, every problem begins to resemble a nail." Abraham Maslow