Search code examples
cnotation

Why sciencific notation for "(double)123456" with "%.4g" conversion is "1.235e+05" instead of 1.234e+05


For me, it seems normal to be 1.234e+05 when using this conversion, because when we revert it with '"%f\n", 1.235e+05' we get 123500.000000 instead of wished "123400.000000".

Actually the question is: why it is skipped the "4" digit ?!

Following example will reinforces what I wanted to say:

#include <stdio.h>

int main(int argc, char **argv)
{
    char x[100];
    sprintf(x, "%.4g", (double)123456);
    printf(">%s<\n", x);
    printf("%f\n", 1.235e+05);
    return 0;
}

Thanks, Valentin


Solution

  • printf with limited precision does not truncate; it rounds per the current rounding mode. The default mode is round-to-nearest. Since the 123456 is closer to 123500 than to 123400, the former value is printed.