Use printf to format floats without decimal places if only trailing 0s

You can use the %g format specifier:

#include <stdio.h>

int main() {
  float f1 = 12;
  float f2 = 12.1;
  float f3 = 12.12;
  float f4 = 12.1234;
  printf("%g\n", f1);
  printf("%g\n", f2);
  printf("%g\n", f3);
  printf("%g\n", f4);
  return 0;
}

Result:

12
12.1
12.12
12.1234

Note that, unlike the f format specifier, if you specify a number before the g it refers to the length of the entire number (not the number of decimal places as with f).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)