Search code examples
cioformatting

Can you print an integer in scientific notation?


I know that in C, you can print floats and doubles in scientific notation using "%e" and "%le" respectively and that you can print integers using "%d". Is there a way to print integers using scientific notation? I tried "%de", but that didn't work. For instance, I want 6000000 to print as 6e+06.


Solution

  • Can you print an integer in scientific notation?

    A simple approach is to convert to a double and then print. @Eric Postpischil

    printf("%e\n", (double) some_int_type_object);
    

    This is insufficient when the integer precision and value exceeds double - typically about 53 bits.

    Recommend to use long double to handle wider integer types. This still may not meet precision requirements.

    printf("%Le\n", (long double) some_integer_type_object);
    

    To portably handle 64-bit integers obliges custom code.