cdoubledecimalscientific-notationdecimal-point

Scientific notation in c


How can I print the output as 123.4e+04 by increasing the number of digits before the comma instead of 1.234e+06 when using scientific notation in c

I tried the %*.*e representations, as shown below, but it didn't work. It shows any result as a single digit before the comma.

#include <stdio.h>
int main() {
    double num =12340000;
    printf("%1.1e\n", num);
    printf("%2.1e\n", num);
    printf("%2.2e\n", num);
    printf("%3.1e\n", num);
    printf("%4.1e\n", num);
    printf("%5.1e\n", num);
    printf("%5.2e\n", num);
    printf("%6.3e\n", num);
    printf("%8.4e\n", num);
    printf("%3.0e\n", num);
}
1.2e+07
1.2e+07
1.23e+07
1.2e+07
1.2e+07
1.2e+07
1.23e+07
1.234e+07
1.2340e+07
1e+07

Solution

  • How can I print the output as 123.4e+04 by increasing the number of digits before the comma instead of 1.234e+06 when using scientific notation in c

    Only by performing the formatting yourself, or finding some third-party library that will do it for you, or relying on some extension that your C implementation happens to provide. The printf-family functions, as described in the language specification, do not provide such an option.

    Standard printf and its siblings offer two main alternatives for formatting floating-point values:

    For cases where the range of values to be formatted is very large, there is also %g, which chooses between the other two based on the magnitude of the value being formatted.

    I'm unsure why it's important to you to vary the number of digits before the decimal point in a scientific-notation-like format, but here are a couple of alternatives that might suit: