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

后端 未结 3 1493
滥情空心
滥情空心 2020-12-08 18:55

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

相关标签:
3条回答
  • 2020-12-08 19:28

    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
    
    0 讨论(0)
  • 2020-12-08 19:28

    For what it's worth, here's a simple ObjC implementation:

    // Usage for Output   1 — 1.23
    [NSString stringWithFormat:@"%@ — %@", [self stringWithFloat:1], 
                                           [self stringWithFloat:1.234];
    
    // Checks if it's an int and if not displays 2 decimals.
    + (NSString*)stringWithFloat:(CGFloat)_float
    {
        NSString *format = (NSInteger)_float == _float ? @"%.0f" : @"%.2f";
        return [NSString stringWithFormat:format, _float];
    }
    

    %g wasn't doing it for me — this one yes :-) Hope it's useful to some of you.

    0 讨论(0)
  • 2020-12-08 19:31

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

    0 讨论(0)
提交回复
热议问题