What is the difference between% 0.2lf and% .2lf as printf placeholders?

I know that adding any number 0 to the width of the placeholder implements zero padding. For example, printf("%02d", 6); prints 06 .

But what does a single 0 do before placeholder precision does? For example, for printf("%0.2lf", 0.123); and printf("%.2lf", 0.123); conclusion 0.12 .

If he does nothing, is there a preferred format?

+6
source share
4 answers

They are "equivalent." If you use "% 07.2", it will make a difference by adding extra zeros on the front panel.

Edit: Initially, it was "% 04.2", which, of course, does not matter, because a float with two decimal places always has a width of 4 times.

+6
source


%3.2f //(print as a floating point at least 3 wide and a precision of 2)

%0.2lf //(print as a floating point at least 0 wide and a precision of 2)

%.2lf //(print as a floating point at least 0(default) wide and a precision of 2)

+3
source

Blockquote

Basically, when we % wp f to output w refer to the minimum number of positions that should be used to display the value, and p refers to the number of digits after the decimal point. %3.2f floating point having 3 wide and 2 numbers after decimal

%0.2f with a floating point of at least 0 width and 2 numbers after the decimal

%.2f floating point at least 0 (default) and precision 2)

But don’t understand about width 0, if you use %0.2f , it can automatically adjust the minimum width.

+1
source

These examples should show the difference:

"%0.2lf", 0.123 β†’ 0.12 (zero filled minimum width of 0, 2 decimal places).

"%6.2lf", 0.123 β†’ __0.12 (space at least 6, 2 decimal places wide).

"%06.2lf", 0.123 β†’ "%06.2lf", 0.123 (zero minimum width of 6, 2 decimal places).

"%0.6lf", 0.123 β†’ 0.123000 (minimum width is 0, 6 decimal places).

The first zero indicates zero padding, followed by the minimum width, which has a default value of 0. Thus, it is actually ignored by itself (since you cannot skip width 0).


By the way, the correct form is %f , not %lf for printf .
+1
source

All Articles