Change number of digits after comma depending on the situation

Asked

Viewed 1,522 times

0

I know I can get a limit of digits after the comma with %.2f for float and %.2lf for 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, the same will appear - but, if the number ends at zero, decrease this limit: in the case of 310.10, would be 310.1 (and the numbers will vary).

When compiling the programming below with 16 and 455 the result will be 436.10, but I want to show you how 436.1, without modifying the other results which, 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;
}
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

3

  • %g is not working the way you wanted it to, since the numbers will vary, turn into a scanf and will be stored in a float or double variable and not a particular number. Even with a %g variable it will not work and even changing to %.5g for example the value would not be acceptable because it would also modify the numbers before the comma.

  • 1

    You didn’t put that in your question, I answered based on what you asked and showed that according to what’s in your question, it works. You can ask another question by putting your real code and what is going wrong and what should be right, in this one has already been answered what was asked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.