How to cout a float number with n decimal places
89,085
You need std::fixed
and std::setprecision
:
std::cout << std::fixed << std::setprecision(3) << a;
These require following header:
#include <iomanip>
Author by
Muhammad Barrima
Updated on October 25, 2020Comments
-
Muhammad Barrima over 3 years
Possible Duplicate:
How do I print a double value with full precision using cout?float a = 175.; cout << a;
If I run the previous code I'll get just 175, how can I cout the number with (for example) 3 decimal places even they were zeros .. How can I print "175.000" ?!
-
Kerrek SB over 11 yearsAhh, iostreams... seamlessly combining the speediness of a turtle and the beauty of Andrew LLoyd-Webber.
-
Kyle almost 5 yearsFor future reference, if you're outputting multiple values, you only need to pass the manipulators once:
float a = 2.5; float b = 3.5; std::cout << std::fixed << std::setprecision(3); std::cout << a << std::endl; std::cout << b << std::endl;
-
ReinstateMonica3167040 over 4 years@MuhammadBarrima Please accept this answer if that's what you needed to show that this question is resolved.