Search code examples
cprintfnumber-formatting

Is it possible, with printf, to have the dot "floating" depending on the value?


I want my converted string to always take N characters, a little like this:

100000.f -> "00100000.0"
10000.f  -> "00010000.0"
1000.f   -> "00001000.0"
100.f    -> "00000100.0"
10.f     -> "00000010.0"
1.f      -> "00000001.0"
0.1f     -> "00000000.1"
0.01f    -> "0000000.01"
0.001f   -> "000000.001"
0.0001f  -> "00000.0001"

or like this:

100000.f -> "100000.000"
10000.f  -> "10000.0000"
1000.f   -> "1000.00000"
100.f    -> "100.000000"
10.f     -> "10.0000000"
1.f      -> "1.00000000"
0.1f     -> "0.10000000"
0.01f    -> "0.01000000"
0.001f   -> "0.00100000"
0.0001f  -> "0.00010000"

Of course the string can grow larger if the decimal part is too large, but so far I'm not concerned by that.

Should I dynamically generate the "%05.5f" format string?


Solution

  • No, you don't have to generate string dynamically. You can just do it like this:

    printf("%0*.5f", width, value);
    

    You can customize it even furthrer, to have variable precision:

    printf("%0*.*f", width, precision, value);