I have a list of float
values and I want to print them with cout
with 2 decimal places.
For example:
10.900 should be printed as 10.90 1.000 should be printed as 1.00 122.345 should be printed as 122.34
How can I do this?
( setprecision
doesn't seem to help in this.)
By using the setprecision function, we can get the desired precise value of a floating-point or a double value by providing the exact number of decimal places. If an argument n is passed to the setprecision() function, then it will give n significant digits of the number without losing any information.
We use the printf() in C++ to display strings in the desired format. It is a part of the cstdio header file. We use the %. 2f format specifier to display values rounded to 2 decimal places.
For the number of decimal places stated, count that number of digits to the right of the decimal and underline it. The next number to its right is called the 'rounder decider'. If the 'rounder decider' is 5 or more, then round the previous digit up by 1.
With <iomanip>
, you can use std::fixed
and std::setprecision
Here is an example
#include <iostream> #include <iomanip> int main() { double d = 122.345; std::cout << std::fixed; std::cout << std::setprecision(2); std::cout << d; }
And you will get output
122.34
You were nearly there, need to use std::fixed as well, refer http://www.cplusplus.com/reference/iostream/manipulators/fixed/
#include <iostream> #include <iomanip> int main(int argc, char** argv) { float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 }; std::cout << std::setprecision(2) << std::fixed; for(int i = 0; i < 6; ++i) { std::cout << testme[i] << std::endl; } return 0; }
outputs:
0.12 1.23 12.35 123.45 1234.50 12345.00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With