0

I want to trail the output of a double to 2 decimals or less. Consider following example:

#include <stdio.h>

int main() {
    printf( "%.2f\n", 2.    );
    printf( "%.2f\n", 2.5   );
    printf( "%.2f\n", 2.25  );
    printf( "%.2f\n", 2.125 );
}

The output is

2.00
2.50
2.25
2.12

Is there any way to print the values with less than 2 decimals, in case less are needed? I mean the desired output is

2
2.5
2.25
2.12

Answers with iomanip are allowed. I'm focusing on C++, not C but the example is c-only.

I know, that it is often not possible because double values are not precise, but in my examples they are because all fractional parts are powers of 2

Live example

smac89
  • 39,374
  • 15
  • 132
  • 179
meddle0106
  • 1,292
  • 1
  • 11
  • 22

2 Answers2

2

If the absolute value is known to be between 0.006 and 999.995, you could use format %.3g:

#include <stdio.h>

int main() {
    printf( "%.3g\n", 2.    );
    printf( "%.3g\n", 2.5   );
    printf( "%.3g\n", 2.25  );
    printf( "%.3g\n", 2.125 );
}

Output is

2
2.5
2.25
2.12

But for the general case, trimming the string converted by snprintf() seems required:

void print_double_with_at_most_2_decimal_figures(double x) {
    char buf[400];
    int i = snprintf(buf, sizeof buf, "%.2f", x);
    while (i > 0 && buf[i - 1] == '0')
        buf[--i] = '\0';
    if (i > 0 && buf[i - 1] == '.')
        buf[--i] = '\0';
    fputs(buf, stdout);
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
-3

One way to do it is to take the value that is 2.00 and then assign it to a variable. This should take care of the extra 0's and give you the correct answer.

Max Ho
  • 17