I want to print to screen some numbers with at most 4 digits after decimal point using iomanip
.
I've learned that in default mode setprecision
counts not only the digits after decimal point but also the digits in the integer part. This code
#include <iostream>
#include <iomanip>
int main () {
double numbers[] = {3.141516, 1.01, 200.78901, 0.12345};
int len = sizeof(numbers) / sizeof(numbers[0]);
std::cout << std::setprecision(4);
for (int i = 0; i < len; ++i) {
std::cout << numbers[i] << '\n';
}
return 0;
}
outputs:
3.142
1.01
200.8
0.1235
But what I want is: (at most 4 digits after decimal point without trailing zeros)
3.1415
1.01
200.789
0.1235
Is iomanip
capable of doing this? Without using other tricks (like round
)?
EDIT
It seems that I haven't made it clear enough. My question is iomanip
specific
All I want to know is whether iomanip
is capable of doing things I've described because iomanip
is said to be the standard library for input/output manipulators. The posted question is
Is
iomanip
capable of doing this?
It's more like "is it supported" rather than "give me any solution".
I have searched it again, looked up iomanip
references hoping for a clean and compact way to format floating numbers for at most n
digits, using unnecessary libraries as little as possible.
And there seems to be no standard way to achieve this.