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

6 answers

Looks like I figured out a simple job:

void print(float f) {
  f = floor(f * 100.0f + 0.5f) / 100.0f;
  cout << f;


will solve the most common cases. One thing that cannot be solved is f> 10e7, cout will print f in scientific notation.



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.



This is the default floating point behavior for iostream. Just set the precision to the maximum number of digits (5 in your example) and output to the stream as usual.



There is no way to indicate this. You can specify the exact number of digits after the decimal point (to add zeros if necessary) or the maximum number of significant digits, but not the maximum number of digits after the decimal point.

NOTE. Xeo answered this first in a comment.



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';



1.2 1.2e-06
1.20 0.00
1.2 1.2e-06




Try the following:

char buf[5];
int l = snprintf(buf, sizeof buf, "%.2f", x);
if (!strcmp(buf, "0.00")) printf("0\n");
else printf("%.*g\n", l-1, x);




All Articles