Getting printf () to remove trailing ".0" values

I need to print floating point numbers with the following formatting requirements:

  • 5.12345 should only be displayed 5.1

  • 5.0should only 5(without .0)

  • 5.0176should be displayed only 5(without .01)

I thought I printf()could do something like this ... but now I can not get it to work.

+5
source share
6 answers

You can get closeness to the results you want to use using "% g"

#include <stdio.h>

int main(int argc, char* argv[])
{
        printf("%.6g\n", 5.12345f);
        printf("%.6g\n", 5.0f);
        printf("%.6g\n", 5.0176f);
        return 0;
}

Output:

5.12345
5
5.0176

"% g" will remove trailing zeros.

+8
source

, 1 , 0, . :

// prints the float into dst, returns the number
// of chars in the manner of snprintf. A truncated
// output due to size limit is not altered.
// A \0 is always appended. 
int printit(float f, char *dst, int max) {
  int c = snprintf(dst, max, "%.1f", f);

  if(c > max) {
    return c;
  }

  // position prior to '\0'
  c--;

  while(dst[c] == '0') {
    c--;
    if(dst[c] == '.') {
      c--;
      break;
    }
  }
  dst[c + 1] = '\0';  
  return c + 1;
}

int main(void) {
  char num1[10], num2[10], num3[10];
  printit(5.12345f, num1, 10);
  printit(5.0f, num2, 10);
  printit(5.0176f, num3, 10);
  printf("%s\n%s\n%s\n", num1, num2, num3);
}
+2

, , . , .

, printf, .

char *BuildConditionalFormat(double val)
{
    int tenths = (int)(val * 10) % 10;
    if (tenths == 0)
        return ".0f";
    return ".1f";
}

/* test rig */
float f = 5.0;
printf(BuildConditionalFormat(f), f); /* -> 5 */
f = 5.13;
printf("\n");
printf(BuildConditionalFormat(f), f); /* -> 5.1 */
printf("\n");

, , , 5.1 → 5. ? 5.1 ( ) float - 5.09999 .

, floor() ceil() ...

+1

printf() . :

printf("%.1f", 5.12345f);

5.1.

, , , . (, - ".0176", , ?)

+1

, float sprintf(), , , . float , - .

+1

printf '.', , , , .

0

All Articles