Search code examples
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:

    • via a %e conversion specifier, which is what you are now using. The documentation for this specifies that it provides exactly one digit before the decimal point.

    • via a %f conversion specifier, which uses plain decimal notation, not scientific notation.

    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:

    • if you are simply scaling outputs, such that you expect the exponent part to have some specific value, then scale the value manually, format it using %f and, optionally, add an exponent part manually. Example:

      double x = 12345.67;
      printf("%8.2fe+03", x / 1000);
      // prints "   12.35e+03"
      

      That doesn't seem to be exactly what you asked, but similar could be applied to that.

    • For a general-purpose implementation, you could consider formatting your number as a string, using sprintf with %e, then adjusting the position of the decimal point and the value of the exponent in the resulting formatted string before printing (left as an exercise).