1

When I print a float number with "%f", it prints a float with 6 digits, but I don't want to print extra zeros. I can to use for example "%.3f" to print just 3 digits, but I want to print a float with number of random digits ,and using "%.{number}f" is not my answer. for example in:

#include <stdio.h>
int main()
{
    float a, b;
    printf("Please enter a number: ");
    scanf("%f", &a);
    printf("Please enter another number: ");
    scanf("%f", &b);
    printf("%f", a / b);
    return 0;
}

a/b can have even decimal digits. Of course, my question also applies to double and long double too.

Parsa Saberi
  • 105
  • 7
  • 3
    Can you give an example for what you try to do? What is your expected output? – black Nov 01 '20 at 20:34
  • 1
    Use `"%g"` (or `"%lg"`) which will only print the needed number of digits. (e.g. for `1.0` it will only output `1`, for `1.25` it will output `1.25`) – David C. Rankin Nov 01 '20 at 20:42
  • @Weather Vane why are you recommending `sprintf()` instead of `snprintf()`? – DarkAtom Nov 01 '20 at 23:56
  • @Weather Vane The OP is obviously a beginner, and you probably shouldn't recommend such practice to beginners, because sooner or later they are going to make the mistake of using it when not appropriate. – DarkAtom Nov 02 '20 at 00:08
  • @DarkAtom. So why are recommending not checking the return value from `scanf()` in your code? – Weather Vane Nov 02 '20 at 00:10
  • Because the OP is also not doing it. Checking against buffer overflows is much more important then checking for validity of the input in toy programs. – DarkAtom Nov 02 '20 at 00:13
  • @DarkAtom please set a good example. – Weather Vane Nov 02 '20 at 00:14

2 Answers2

1

There are many ways to remove the extra zeros.

  1. Easiest way is to use %g as the format specifier in the printf statement. Eg. printf("%g",a/b);. This is remove the extra zeros after the decimal.

  2. You can use printf("%.0d%.4g\n", (int)(a/b)/10, (a/b)-((int)(a/b)-(int)(a/b)%10));.

  3. You can use a separate function to remove the extra zeros but it is a tedious process. First transfer all the digits to a string and remove the unwanted zeros from the end.

  4. You can also use %.2f format specifier to reduce the zeros. Eg. printf("%.2f",a/b); - this can be used where you want to print the exact number of digits after the decimal point. %.<the number of digits to be printed after decimal point>f.

prithvi
  • 51
  • 1
0

Here is a piece of code to print n non-zero decimal digits:

#include <stdio.h>
#include <math.h>

int main(void)
{
    int n;
    float a, b;
    scanf("%f %f %d", &a, &b, &n);
    float result = a / b;
    printf("%d", (int)result);
    int decimal = (int)trunc(result * pow(10, n)) % (int)pow(10, n);
    if (decimal != 0)
        while (decimal % 10 == 0)
            decimal /= 10;
    printf(".%d\n", decimal);
}
DarkAtom
  • 2,589
  • 1
  • 11
  • 27