Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting printf() to drop the trailing ".0" of values

Tags:

c

printf

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

  • 5.12345 should display only 5.1

  • 5.0 should only 5 (without the .0)

  • 5.0176 should display only 5 (without the .01)

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

like image 650
Susanna Avatar asked Mar 09 '10 19:03

Susanna


2 Answers

You can get kind of close to the results you want 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.

like image 135
Jason Avatar answered Sep 21 '22 09:09

Jason


Sounds like you want to print 1 decimal place, and if that place is 0, drop it. This function should work fine:

// 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);
}
like image 30
Johannes Schaub - litb Avatar answered Sep 24 '22 09:09

Johannes Schaub - litb