Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

printf

Is it possible to format a float in C to only show up to 2 decimal places if different from 0s using printf?

Ex:

12 => 12

12.1 => 12.1

12.12 => 12.12

I tried using:

float f = 12; printf("%.2f", f) 

but I get

12 => 12.00

12.1 => 12.10

12.12 => 12.12

like image 814
epignosisx Avatar asked Mar 09 '12 03:03

epignosisx


People also ask

How do I print float values without trailing zeros?

print( '{:,g}'. format( X ) worked for me to output 3 where X = 6 / 2 and when X = 5 / 2 I got an output of 2.5 as expected. old question, but.. print("%s"%3.140) gives you what you want.

How do you print a float without a decimal?

printf("%. 0f\n", my_float); This will tell printf to include 0 decimal places of precision (you can, of course, use other values as well).

What is %g in printf?

According to most sources I've found, across multiple languages that use printf specifiers, the %g specifier is supposed to be equivalent to either %f or %e - whichever would produce shorter output for the provided value.

How do I keep 0 after decimal in Excel?

Get to the Format Cells dialog (e.g. by right-clicking a cell and selecting "Format Cells...") On the Number tab, select Number from the list of Categories. Set the Decimal Places box to 6. Hit Ok .


2 Answers

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).

like image 118
mechanical_meat Avatar answered Sep 30 '22 09:09

mechanical_meat


From our discussion in the above answer here is my program that works for any number of digits before the decimal.

#include <stdio.h> #include <stdlib.h> #include <string.h>  int main() {     float f1 = 12.13;     float f2 = 12.245;     float f3 = 1242.145;     float f4 = 1214.1;      int i = 0;     char *s1 = (char *)(malloc(sizeof(char) * 20));     char *s2 = (char *)(malloc(sizeof(char) * 20));      sprintf(s1, "%f", f1);     s2 = strchr(s1, '.');     i = s2 - s1;     printf("%.*g\n", (i+2), f1);      sprintf(s1, "%f", f2);     s2 = strchr(s1, '.');     i = s2 - s1;     printf("%.*g\n", (i+2), f2);      sprintf(s1, "%f", f3);     s2 = strchr(s1, '.');     i = s2 - s1;     printf("%.*g\n", (i+2), f3);      sprintf(s1, "%f", f4);     s2 = strchr(s1, '.');     i = s2 - s1;     printf("%.*g\n", (i+2), f4);      free(s1);     free(s2);      return 0; } 

And here's the output

12.13 12.24 1242.15 1214.1 
like image 39
twain249 Avatar answered Sep 30 '22 08:09

twain249