Change number of digits after the comma depending on the situation [duplicate]

0

I know I can get a digit bound after the comma with %.2f to float and %.2lf to double .

How can I change this limit depending on the occasion?

For example:

Get a two-digit limit with float that would be %.2f , that is, if the number is 310.22 , it will appear - but, if the number ends in zero, lower this limit: in case of 310.10 , would be 310.1 (the numbers will vary).

When compiling the programming below with 16 and 455 the result will be 436.10 , but I want to show it as 436.1 , without modifying the other results that, if they do not end with zero, have two decimal places.

#include<stdio.h>

int main()
{
    double d,km,km2,v,k;
    scanf("%lf%lf",&d,&km);
    v=d*30;
    km2=km*0.01;
    v=v+km2;
    k=v*0.10;
    v=v-k;
    printf("\n%.2lf",v);
    return 0;
}
    
asked by anonymous 09.07.2017 / 03:54

1 answer

3

You have to use %g . See all possible formatting .

#include <stdio.h>

int main(void) {
    printf("%g\n", 310.0);
    printf("%g\n", 310.1);
    printf("%g\n", 310.12);
}

See running on ideone . And in Coding Ground . Also put it in GitHub for future reference .

    
09.07.2017 / 05:05