How printf or iostream determine the maximum number of digits after a dot
Which format string in a statement printf
or iomanip
in an iostream should I use to print a float in the following format:
- 125.0 => 125
- 125.1 => 125.1
- 125.12312 => 125.12
- 1.12345 => 1.12
- 1234.1235 => 1234.12
In short, print no more than 2 digits after the period, but remove any trailing zeros.
I tried %.2f
it but doesn't work because it prints 125.00 and 125.10 for the first 2 cases.
source to share
iostream uses flags.
In particular, use std::cout << std::setprecision(5)
to set the precision to 5. See setprecision and ios_base :: precision .
If you set the precision without setting fixed , it will use the precision you specified with no trailing zeros. If you set the flag as well fixed
, it will print trailing zeros up to the precision you specify.
printf also uses its own flags. See the documentation on how to use it.
source to share
The family printf
has a format %g
for this purpose (but in some cases also has a different purpose to change% f to% e). As James points out, this is the default behavior with C ++ IOStream; to reset if changed to something else:
#include <iostream>
#include <iomanip>
#include <stdio.h>
int main()
{
printf("%.2g %.2g\n", 1.2, 0.0000012);
std::cout << std::fixed << std::setprecision(2) << 1.2 << " " << 0.0000012 << '\n';
std::cout.setf(std::ios_base::fixed|std::ios_base::scientific, std::ios_base::floatfield);
std::cout << std::setprecision(2) << 1.2 << " " << 0.0000012 << '\n';
}
gives
1.2 1.2e-06
1.20 0.00
1.2 1.2e-06
source to share